Search code examples
cucumbercapybara

Is it possible to select multiple equal elements in capybara?


I'm starting to study automated testing with the following gems capybara,cucumber,SitePrism,webdriver, one thing I see a lot happening in my tests is Input type fields if they repeat.

Some like that:

<input type="text" placeholder="some cool text"/>
<input type="text" placeholder="some cool text"/>
<input type="text" placeholder="some cool text"/>

So I'm wondering, if it is possible to define some value in all fields at the same time, something like:

site.find('[placeholder="some cool text"]').set('A simple string')

I'm having trouble finding an answer to that, there would be no problem making loops to define one at a time, but I have no idea how to select them at the same time.


Solution

  • find is limited to returning one element, if you want multiple you'll want to use all. Using Capybara something like

    page.all('input', text: 'some cool text').each do |inp| 
      inp.set('A simple string')
    end
    

    would do what you're asking. If you wanted to make sure it was exactly 3 matching elements that were handled you would use the count option (there arealsominimum, maximum, and between` options available)

    page.all('input', text: 'some cool text', count: 3).each do |inp| 
      inp.set('A simple string')
    end
    

    Update: Since you've updated the question you could do

    page.all("input[placeholder='some cool text']", count: 3).each do |inp| 
      inp.set('A simple string')
    end
    

    but I would probably use the Capybara provided selector types like

    page.all(:fillable_field, placeholder: 'some cool text', count: 3).each do |inp|
      inp.set('A simple string')
    end