6

In my site I have this list:

<ul class="test">
  <li class="social_1"></li>
  <li class="social_2"></li>
  <li class="social_3"></li>
  <li class="social_3"></li>
</ul>

My question is: how can I count li in my ul class test I have tried this:

my_ul = page.find("ul[class='test']")
my_ul.each do |li|
  pp li['class']
end

but it doesn't work.

Is there anyway to do something like I coded above?

Flip
  • 6,233
  • 7
  • 46
  • 75
Tanapat Sainak
  • 734
  • 1
  • 10
  • 22
  • See http://stackoverflow.com/questions/7245702/watir-webdriver-counting-number-of-items-in-a-ul-list. – Mihai8 Jun 10 '14 at 09:42

3 Answers3

13

assuming ul parent element with id=parent .. you can do it like this

  list = Array.new 
  list = find('#parent ul').all('li')

now you can get list size simply

list.size 

and you can benefit from having all li's in array to collect text also in each li like this

  list = find('#parent ul').all('li').collect(&:text)
jhilan
  • 156
  • 5
10

I'd advise using the new RSpec 3 syntax for counting elements with Capybara:

it "should have 4 li elements" do
   expect(find('ul.text')).to have_selector('li', count: 4)
end

More information here: https://github.com/jnicklas/capybara#querying

JellyFishBoy
  • 1,658
  • 1
  • 17
  • 25
  • Thanks for your great answer @JellyFishBoy! I'm glad I scrolled down. The new rspec 3 syntax will wait until the condition is met, or up to the rspec timeout. So it will allow for some time for the condition to be true. – Ryan Grow Mar 31 '20 at 21:44
1

Use page.all("ul.test li").size

Srikanth
  • 265
  • 2
  • 8