Search code examples
ruby-on-railsrspeccapybaracapybara-webkit

Is it possible to fill_in a number field wo/ labels with Capybara?


I have a number field, that takes a :product_quantity with a button after it saying "Add to Cart". My test works without adjusting the number_field but when I uncomment this line:

product_from_shop.fill_in 'quantity', with: 5

Stuff blows up. Capybara::ElementNotFound

It's about this line in my view:

<%= f.number_field :product_quantity, value: booking.product_quantity, min: 1, max: 999, title: 'quantity' %>

I tried several approaches, also searching for the class or id. Non work. There is no label, that would clutter my view.

title worked fine in other cases, without a form.

Also: I am using capybara webkit, because it uses JS.


Solution

  • fill_in uses the :fillable_field selector which will find any visible input or textarea area element except of type submit, image, radio, checkbox, or file. It will find those elements id, name or placeholder attributes or by the text in an associated label element. Since you don't have an associated label you're down to id, name or placeholder attribute. Assuming product_from_shop is a wrapper element on the page you're using to scope this fill_in then

    product_from_shop.fill_in '<something>_product_quantity', with: 5
    

    should find and fill_in the element by id - will depend on what model type the form is for (just look at the actual HTML to see what id was assigned).

    If the product quantity field is the only fillable field inside product_from_shop you could also do

    product_from_shop.fill_in with: 5 # same as product_from_shop.fill_in nil, with: 5
    

    If none of those will work for you, you can move to using something like

    product_from_shop.find(<more complicated query>).set '5'
    

    To clarify your comment about title working previously - The title attribute is only matched when finding links and buttons.