Skip to content

Instantly share code, notes, and snippets.

@Fivell
Forked from faun/have_xml.rb
Created December 18, 2013 17:00
Show Gist options
  • Save Fivell/8025849 to your computer and use it in GitHub Desktop.
Save Fivell/8025849 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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment