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

Tanapat Sainak picture Tanapat Sainak · Jun 10, 2014 · Viewed 7.7k times · Source

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?

Answer

jhilan picture jhilan · Jun 11, 2014

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)