嗨,我可以建议你使用自定义匹配器.
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
不再需要自己动手了.我们每天使用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模板进行严格验证.
尝试一下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
你运行测试时,它会检查以确认收到的有效负载与测试将通过的预期(批准的)有效负载相匹配如果匹配,则测试失败
归档时间: |
|
查看次数: |
7134 次 |
最近记录: |