我有一个RSS提要,我正在写一个RSpec测试。我想测试XML文档是否具有正确的节点和结构。不幸的是,我找不到任何关于如何以干净的方式做到这一点的好例子。我只发现了一些半实现的解决方案和过时的博客文章。如何使用RSpec测试XML文档的结构?
答案 0 :(得分: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
可在此处找到完整示例 https://gist.github.com/Fivell/8025849
答案 1 :(得分:6)
不再需要自己动手了。我们每天使用https://github.com/mbklein/equivalent-xml上的 equivalent-xml 匹配器处理此问题。
require 'rspec/matchers'
require 'equivalent-xml'
...
expect(node_1).to be_equivalent_to(node_2)
具有像空格保存这样的边缘情况的选项。
您的另一个选择是使用正式的XSD模板进行严格验证。
答案 2 :(得分: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
我正在验证的JSON位于名为spec/fixtures
的{{1}}文件夹中
提取上述代码段的实现可用here
它是如何工作的,你提供了一个预期的Payload,JSON,XML,TXT和HTML,我相信它在traffic_around_location.approved.json
中支持,当你运行测试时,它会检查确认收到的有效载荷是否符合预期如果匹配则测试将通过(批准的)有效负载,否则测试失败
答案 3 :(得分:0)
context 'POST #join' do
it 'does successfully hit join xml route' do
post :join,
format: :xml
response.content_type.should == "application/xml"
response.should be_ok
end
end
这对我有用。我没有意识到我必须传递格式:: xml。我的连接路由响应/join.xml,我测试这是成功的。