Skip to content

Instantly share code, notes, and snippets.

@pimpin
Forked from faun/have_xml.rb
Last active November 30, 2022 17:37
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save pimpin/65a39d6e932f44b32fd3 to your computer and use it in GitHub Desktop.
Save pimpin/65a39d6e932f44b32fd3 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)
expect(nodes).to_not be_empty
if text
nodes.each do |node|
cdata = node.children.find { |e| e.cdata? }
value_to_check = node.text
value_to_check = cdata.text if cdata
value_to_check.should == text
end
end
true
end
failure_message do |body|
"expected to find xml tag #{xpath} in:\n#{body}"
end
failure_message_when_negated 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
expect(response.body).to have_xml '/xpath/to/match' "content with xpath selector"
end
it "does not have another thing" do
expect(response.body)not_to have_xml '/xpath/to/disallow' "content with xpath selector"
end
end
end
@EddieOne
Copy link

line 22 in the first file is wrong still

line 2 in the second file also copied the syntax error

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