Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 929
Tanapat Sainak Avatar asked Nov 29 '22 00:11

Tanapat Sainak


2 Answers

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)
like image 59
jhilan Avatar answered Dec 06 '22 23:12

jhilan


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

like image 28
JellyFishBoy Avatar answered Dec 07 '22 00:12

JellyFishBoy