3

使用 RSpec 我如何/应该测试以确保元素存在并具有指定的值

在我的示例中,我希望确保我有一个值为 1.0 的 EnvelopeVersion,我还希望查看一个测试以确保 EnvelopeVersion 存在

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

我试过这个,但它失败了未定义的方法“has_node?” 为了 #

it 'should create valid header' do
   doc = GEM::xml_header
   doc.should have_node("EnvelopeVersion ")
end 
4

2 回答 2

3

您的解决方案可以简化:

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

可以简化为:

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

Nokogiri 有两种主要的“查找”方法:searchat. 它们是通用的,因为它们同时接受 XPath 和 CSS 访问器。search返回所有匹配节点的 NodeSet,并at返回第一个匹配的节点。

还有一些方法at_xpathat_css如果你想要一些更易记的东西,还有xpathand css

于 2012-08-22T16:11:30.910 回答
1

我最终在我的测试中使用 nokogiri 来解析生成的 xml 并查询它

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
于 2012-08-22T11:16:29.623 回答