Skip to content

Instantly share code, notes, and snippets.

@scottbarrow
Created July 18, 2018 20:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save scottbarrow/d3928f6e9e64b51144b341f8aac2c0cd to your computer and use it in GitHub Desktop.
Save scottbarrow/d3928f6e9e64b51144b341f8aac2c0cd to your computer and use it in GitHub Desktop.
require 'nokogiri'
+
+RSpec::Matchers.define :have_xml do |xpath, condition|
+ match do |body|
+ doc = Nokogiri::XML::Document.parse(body)
+ nodes = doc.xpath(xpath)
+ expect(nodes).not_to be_empty
+
+ if condition
+ condition.keys.each do |key|
+ case key
+ when :text
+ nodes.each do |node|
+ expect(node.content).to eq condition[key]
+ end
+ when :attribute
+ nodes.each do |node|
+ condition_hash = condition[key].stringify_keys
+ values = condition_hash.values
+ keys = condition_hash.keys
+
+ expect(node.attributes.keys).to include *keys
+ expect(node.attributes[condition_hash.keys[0]].value).to eq values[0]
+ end
+ end
+ 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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment