Multiline step arguments with Cucumber
I’ve been doing lots of Cucumber testing lately and I must say, it’s a great tool. I have stumbled upon one problem though, which are multiline step arguments. The Cucumber wiki covers most cases, but what happens when the HTML list or table you want to check is not a proper table, but just some divs, mixed with tables and/or uls?
There is a pretty easy way to do this. Cucumber History.txt file says that table_at method is deprecated, and we should use element_at instead. Also, element_at takes a CSS selector as an argument. So we can just choose any container element from the HTML, pass it to Nokogiri, and get an array of text.
Example: if we had this HTML code
<div id="search_results"> <% @people.each do |person| %> <div class="result"> <div class="image"><img src="/img/default.png" /></div> <div class="information"> <ul> <li class="name"><%=h person.name %></li> <li class="email"><%=link_to h(person.email), "mailto:#{person.email}" %></li> <li class=""></li> </ul> </div> </div> <% end %> </div>
and we wanted to check if the search results are what we expect, we could write a Cucumber step that looks like this:
Then /^I should see the following search results$/ do |searches| search_results = element_at('div#search_results') node = Nokogiri::HTML("<html>#{search_results.element}</html>").css('.information ul li.name') actual_table = node.map { |name| name.inner_html.strip } searches.diff!(actual_table) end
and call it like this:
Then I should see the following search results | John | | Mike | | Susan |
Done!
