This is either awesome or incredibly stupid.

If you’re anything like me, you’re not only strikingly handsome but also in a weird love affair with the idea of validating an arbritarily deep hierarchy of HTML tags from within cucumber. Like when oh I don’t know.. Say you have an ul like so:

<ul>
  <li><a href="/a">A</a>
    <ul>
      <li><a href="/a/1">A.1</a>
        <ul>
          <li><a href="/a/1/1">A.1.1</a></li>
        </ul>
      </li>
    </ul>
  </li>
  <li><a href="/b">B</a>
    <ul>
      <li><a href="/b/1">B.1</a></li>
    </ul>
  </li>
</ul>

Then you want to be able to write the following steps:

Then I should see "A.1.1" under "A.1", "A"
And I should see "B.1" under "B"
And I should see "A" besides "B"

Or maybe you don’t. But at least after drinking some Mac Queen’s Nessie Whisky Malt Red Beer, I for one certainly did.. Also: working with Nokogiri & XPath can be oddly ruminant!

And here it is, the (soon-to-be) patented prototype implementation of said (possibly stupid) awesomity:

Then /^I should see "([^\"]+)" (under|besides) ((?:"[^\"]+"(?:, )?)+)$/ do |needle, position, haystack|
  haystack = haystack.split('"')
  haystack = haystack.values_at(*(0..haystack.length-1).select(&:odd?))
 
  doc = Webrat.nokogiri_document(response)
  exists_within_or_besides([needle] + haystack, position, doc).should be_true
end
 
def exists_within_or_besides(what, where, node)
  nodes = node.search("*[text()='#{what.pop}']").to_a
  return true if what.empty? and !nodes.empty?
  nodes.collect!{|node| node.description.block? ? node : node.parent}
  nodes.collect!{|node| node.parent.children} if where == "besides"
  nodes.any? {|node| exists_within_or_besides(what.dup, where, node)}
end

Post a Comment

Your email is never published nor shared. Required fields are marked *

*
*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre lang="" line="" escaped="">

Aether Child Theme by altamente decorativo & bendler.tv | built on Thematic Framework