Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Iterating through items in Capybara

I've got a page containing multiple elements of class .block. In Capybara, I want to be able to loop through and refer to each of the elements with this class before completing an action.

However, none of the code I've tried so far has worked. Here's what I've tried:

within('.block:nth-child(1)') do
  find('.Button').click
end

page.find('.block').all.first.find('Button').click

page.find('.block').all[1].find('Button').click

Any ideas?

like image 256
Michael Avatar asked Sep 14 '12 15:09

Michael


1 Answers

You want to use the all method (see http://rubydoc.info/github/jnicklas/capybara/Capybara/Node/Finders#all-instance_method).

An example of outputting the text of each element (ie iterating) with class 'block' would be:

page.all(:css, '.block').each do |el|
    puts el.text
end

page.all returns an array of matching elements. So if you just want the second matching element, you can do:

page.all(:css, '.block')[1]  #Note that it is 0-based index
like image 197
Justin Ko Avatar answered Oct 18 '22 22:10

Justin Ko