1

In the page are many submit buttons with label "Add to Cart". I would like to select the first add to cart button. What is the best way to match the first add to cart button? The buttons are defined as follows. They are submit buttons with label "Add to Cart"

 <input type="submit" name="commit" value="Add to Cart">

I have tried

all('input[type="submit"]')[0] 

This will select the first submit button. How can i also make sure it has label "Add to Cart"? Thanks!

kofhearts
  • 3,607
  • 8
  • 46
  • 79
  • Possible duplicate of [Capybara Ambiguity Resolution](https://stackoverflow.com/questions/13132506/capybara-ambiguity-resolution) – fabdurso Aug 22 '18 at 09:00

2 Answers2

2

There are many ways to do what you want, some of which would require you to show more of the HTML structure. However, the easiest is probably to take advantage of the fact you can pass any selector type to first/all/find and use the builtin :button selector - https://github.com/teamcapybara/capybara/blob/3.6_stable/lib/capybara/selector.rb#L145 - which will find by the button value.

first(:button, 'Add to Cart')

or

all(:button, 'Add to Cart')[0] # more useful if you want other than the first

Note that all does have the downside that elements returned by it are not reloadable, but if your page isn't changing and you're going to interact with the element immediately it shouldn't be an issue.

Thomas Walpole
  • 48,548
  • 5
  • 64
  • 78
1

This should do it:

find("input[type='submit']", match: :first)
Pang
  • 9,564
  • 146
  • 81
  • 122