assert_xpath Queries XHTML Details

Our Wiki should parse a little more YAML:

  def test_format_yaml
    yar = YarWiki.new('WikiTestPage')
    yar.save_page "--- !omap\n- key2: value2\n- key1: value1"
    x = Builder::XmlMarkup.new
    yar.format_yaml x
    assert_xml x.target!
    assert_xpath '/ul/li/strong[ . = "key2" ]'
  end

We are growing a new service to test HTML, and we are starting to test the YarWiki object directly without testing its controller. XPath is the best way to test relations between arbitrarily complex HTML, so here are some simple assertions that use it:

  def assert_xml(contents)
    @xdoc = Document.new(contents.to_s)
  end

  def assert_xpath(path, message = '')
    assert_not_nil XPath.first(@xdoc, path),
                   message +
                   "\nseeking: #{path.inspect} in\n#{@xdoc.to_s}"
  end

To test-first a new test service, we make it fail first and then examine its diagnostics. If we change the strong to strung, the assertion should tell us enough about the situation to avoid further debugging:

  1) Failure:
test_format_yaml(WikiControllerTest)
    [./test/functional/wiki_controller_test.rb:47:in `assert_xpath'
     ./test/functional/wiki_controller_test.rb:58:in `test_format_yaml']:
seeking: "/strung" in
<strong>--- !omap
key2: value2
key1: value1</strong>.
<nil>expected to not be nil.

That failure is beautiful; it tells us exactly what's wrong. Given an unexpected failure in an arbitrarily complex XPath, we have much more to work with than just "<nil>expected to not be nil." And we have that, too!

The next test case will upgrade

Get Test Driven Ajax (on Rails) now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.