Skip to content

Instantly share code, notes, and snippets.

@faun
Created December 13, 2012 21:14
Show Gist options
  • Star 8 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • Save faun/4279964 to your computer and use it in GitHub Desktop.
Save faun/4279964 to your computer and use it in GitHub Desktop.

Rspec custom matchers for xml using Nokogiri XPath selector and optional content to match within selection. See matcher_spec.rb for usage.

Place have_xml.rb in your {Rails.root}/spec/support/matchers directory

Adapted from: Testing XML with rspec, xpath and libxml

require 'nokogiri'
RSpec::Matchers.define :have_xml do |xpath, text|
match do |body|
doc = Nokogiri::XML::Document.parse(body)
nodes = doc.xpath(xpath)
nodes.empty?.should be_false
if text
nodes.each do |node|
node.content.should == text
end
end
true
end
failure_message_for_should do |body|
"expected to find xml tag #{xpath} in:\n#{body}"
end
failure_message_for_should_not do |response|
"expected not to find xml tag #{xpath} in:\n#{body}"
end
description do
"have xml tag #{xpath}"
end
end
describe "thing" do
context 'xml'
before do
get "/a_thing", {:format => :xml}
end
it "has a thing" do
response.body.should have_xml '/xpath/to/match' "content with xpath selector"
end
it "does not have another thing" do
response.body.should_not have_xml '/xpath/to/disallow' "content with xpath selector"
end
end
end
@pimpin
Copy link

pimpin commented Mar 2, 2016

I've made updates here

  • with expect syntax,
  • including @benissimo "CDATA unsensitive parsing feature"

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment