Posts Tagged xml

test_xml 0.1 released – Testing your XML has never been easier!

Tuesday, April 19th, 2011

A couple of days ago Pavel Gabriel and I released a refreshed version of the test_xml gem.

test_xml helps you asserting that XML is the way your specification wants it. It provides some simple assertions and runs with Test::Unit, MiniTest, RSpec2 and Cucumber. It’s perfect for testing REST services emitting XML representations. Internally, it uses Nokogiri for node matching.

Overview

Say your expecting the following XML document from your service (or whatever).

<company>
  <id>1</id>
  <name flavor="funny">Applicake</name>
</company>

Now it is pretty tedious testing this against a string with regexps while skipping newlines or whitespaces and so on. Use test_xml for that!

assert_xml_equal expected, "<company><id>1</id>
  <name>Applicake</name></company>"

As you’re using assert_xml_equal this will fail – the subject is missing the flavor attribute and thus is not equal!

We can do that in RSpec as well!

  expected.should equal_xml expected

This will work. Obviously.

Testing structure, ignoring content

Sometimes you might want to test the tag structure without respecting the content or attributes.

assert_xml_structure_equal expected, "<company>
  <id>One million</id>
  <name>Railslove</name></company>"

Turns out to be true.

Asserting parts, only

Sometimes you might want to check that your XML contains some markup block, which doesn’t need to be the very image of your specification.

assert_xml_contain expected, "<company>
  <name flavor="funny">Applicake</name>
</company>"

Works! This is especially helpful if you’re interested in certain blocks of your markup and not the entire document.

Assertions?

What we got is

  • assert_xml_equal
  • assert_xml_contain
  • assert_xml_structure_equal
  • assert_xml_structure_contain

Pretty obvious what they’re doing, isn’t it? Use ‘em in RSpec if you feel like it.

Give it a try!

Now go and check out the test_xml gem and feel safer when rendering XML. Testing FTW!