XPath matching in Test::Unit
February 12, 2008 | code, rails, ruby, testing, xml
Inspired by an article on adding XPath matching to RSpec. I’m not using RSpec currently, and I also have a need for this functionality in my tests, so I decided to a helper for use in Test::Unit to achieve XPath matching in my tests.
Add a new helper method:
Add the following code to your test/test_helper.rb in order to create the assert_has_xpath method.
#test/test_helper.rb
require 'rexml/document'
# Asserts that the specified xpath matches
# at least once in the given document
def assert_has_xpath (xpath, doc)
doc = doc.is_a?(REXML::Document) ? doc : REXML::Document.new(doc)
match = REXML::XPath.match doc, xpath
assert !match.empty?, "Missing xpath '#{xpath}' in document: #{doc}"
end
Optionally, you can add the above to a module and include it in your test_helper, or in your individual tests.
Use the helper in your tests:
Now, in your tests, you can do something like the following
#model.rb
def to_xml options = {}
xml = options[:builder] ||= Builder::XmlMarkup.new(options)
xml.toys{
xml.toy "ball"
xml.toy "iPhone"
}
end
#model_test.rb
def test_create_xml_creates_toys
model = Model.new
xml = model.to_xml
assert_has_xpath "/toys[toy='iPhone']", xml
end
And voila! You now have XPath testing in your Test::Unit tests.