Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to test XML file using RSpec?

Tags:

xml

ruby

rss

rspec

I have an RSS feed that I am writing an RSpec test for. I want to test that the XML document has the correct nodes and structure. Unfortunately, I can't find any good examples of how to do this in a clean way. I have only found some half-implemented solutions and outdated blog posts. How can I test the structure of an XML document using RSpec?

like image 259
Andrew Avatar asked Dec 12 '13 19:12

Andrew


1 Answers

Hi I can recommend you to use custom matcher for this.

 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

Full example can be found here https://gist.github.com/Fivell/8025849

like image 165
Fivell Avatar answered Sep 30 '22 17:09

Fivell