Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Testing Nokogiri XML for Attributes

Using RSpec How could/should I test to ensure elements exists and have specified values

In my example I'm looking to ensure I have an EnvelopeVersion with a value 1.0, i would also like to see a test just to ensure EnvelopeVersion exists

def self.xml_header
   builder = Nokogiri::XML::Builder.new do |xml|
  xml.Root{
     xml.EnvelopeVersion "1.0"
  }
   end
   builder.to_xml
end

I've tried this, but it failed undefined method `has_node?' for #

it 'should create valid header' do
   doc = GEM::xml_header
   doc.should have_node("EnvelopeVersion ")
end 
like image 653
Nath Avatar asked Dec 14 '25 05:12

Nath


2 Answers

Your solution can be simplified:

doc = Nokogiri::XML::Document.parse(GEM::xml_header)    
doc.xpath('//Root/EnvelopeVersion').text.should eq("1.0")

can be simplified to:

doc = Nokogiri::XML(GEM::xml_header)    
doc.at('EnvelopeVersion').text.should eq("1.0")

Nokogiri has two main "find-it" methods: search and at. They are generic, in that they accept both XPath and CSS accessors. search returns a NodeSet of all matching nodes, and at returns the first Node that matches.

There are also the methods at_xpath and at_css if you want something a bit more mnemonic, along with xpath and css.

like image 92
the Tin Man Avatar answered Dec 15 '25 17:12

the Tin Man


I ended up using nokogiri in my tests to parse the generated xml and query it

require 'nokogiri'

describe 'function' do
  describe '.xml_header' do
    it 'should create valid header' do
        doc = Nokogiri::XML::Document.parse(GEM::xml_header)    
        doc.xpath('//Root/EnvelopeVersion').text.should eq("1.0")
    end     
  end
end
like image 21
Nath Avatar answered Dec 15 '25 18:12

Nath



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!