Using xml with assert_select

Posted on May 25, 2007

Jamis Buck had a useful article about using xml with assert_tag, and so did Peter Marklund, but I wanted something slightly different.

Normally assert_select uses the @response.body string to test against, but it has another option. It'll take an HTML::Document as its first argument, so you can pass it any xml you like, from any source.

I just added a small helper to test_helper.rb called with_xml.

def with_xml xml, &block
  doc = HTML::Document.new(xml, false, true)
  assert_select doc.root, ':root', &block
end

And here's how to use it:

def test_foo
  xml =<<SNRK
<foo>
  <bar>
  </bar>
</foo>
SNRK
  with_xml xml do
    assert_select 'foo:root bar'
  end
end