O'Reilly logo

Test Driven Ajax (on Rails) by Phlip

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required