How can I count list elements in unordered list? (RSpec/Capybara)
Asked Answered
C

3

7

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?

Claudiaclaudian answered 10/6, 2014 at 9:38 Comment(1)
See #7246202.Eyre
M
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)
Mahalia answered 10/6, 2014 at 23:49 Comment(0)
O
11

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

Optional answered 10/6, 2014 at 14:50 Comment(1)
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.Otha
D
1

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

Dimissory answered 10/6, 2014 at 14:3 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.