如何使用RSpec测试XML文件?

And*_*rew 17 ruby xml rss rspec

我有一个RSS提要,我正在写一个RSpec测试.我想测试XML文档是否具有正确的节点和结构.不幸的是,我找不到任何关于如何以干净的方式做到这一点的好例子.我只发现了一些半实现的解决方案和过时的博客文章.如何使用RSpec测试XML文档的结构?

Fiv*_*ell 7

嗨,我可以建议你使用自定义匹配器.

 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
Run Code Online (Sandbox Code Playgroud)

完整示例可以在这里找到 https://gist.github.com/Fivell/8025849


Joe*_*ger 6

不再需要自己动手了.我们每天使用https://github.com/mbklein/equivalent-xml上equivalent-xml匹配器来解决这个问题.

require 'rspec/matchers'
require 'equivalent-xml'
...
expect(node_1).to be_equivalent_to(node_2)
Run Code Online (Sandbox Code Playgroud)

具有像空白保留这样的边缘情况的选项.

您的另一个选择是使用正式的XSD模板进行严格验证.


bjh*_*aid 1

尝试一下Approvals ,它可以与 rspec 配合使用,我曾用于测试 Json 有效负载,并且它与exercism.io中的 Minitest 一起使用

编辑

  it "returns available traffic information around me" do
    post '/search_traffic_around', {location: [-87.688219, 41.941149]}.to_json
    output = last_response.body
    options = {format: :json, name: 'traffic_around_location'}
    Approvals.verify(output,options)
  end
Run Code Online (Sandbox Code Playgroud)

我正在验证的 JSON 位于spec/fixtures名为的文件夹中traffic_around_location.approved.json

此处提供了提取上述代码片段的实现

它的工作原理是你向它提供一个预期的有效负载、JSON、XML、TXT 和 HTML,我确信它支持,当spec/fixtures你运行测试时,它会检查以确认收到的有效负载与测试将通过的预期(批准的)有效负载相匹配如果匹配,则测试失败