JSON比较解决方案
产生干净但可能很大的差异:
actual = JSON.parse(response.body, symbolize_names: true)
expected = { foo: "bar" }
expect(actual).to eq expected
实际数据的控制台输出示例:
expected: {:story=>{:id=>1, :name=>"The Shire"}}
got: {:story=>{:id=>1, :name=>"The Shire", :description=>nil, :body=>nil, :number=>1}}
(compared using ==)
Diff:
@@ -1,2 +1,2 @@
-:story => {:id=>1, :name=>"The Shire"},
+:story => {:id=>1, :name=>"The Shire", :description=>nil, ...}
(感谢@floatingrock发表评论)
字符串比较解决方案
如果您想要一个固定的解决方案,则应避免使用可能引入错误肯定等式的解析器。将响应主体与字符串进行比较。例如:
actual = response.body
expected = ({ foo: "bar" }).to_json
expect(actual).to eq expected
但是第二种解决方案在视觉上不太友好,因为它使用了序列化的JSON,其中包含许多转义的引号。
定制匹配器解决方案
我倾向于给自己写一个自定义匹配器,它可以更好地查明JSON路径到底在哪个递归槽上不同。将以下内容添加到您的rspec宏中:
def expect_response(actual, expected_status, expected_body = nil)
expect(response).to have_http_status(expected_status)
if expected_body
body = JSON.parse(actual.body, symbolize_names: true)
expect_json_eq(body, expected_body)
end
end
def expect_json_eq(actual, expected, path = "")
expect(actual.class).to eq(expected.class), "Type mismatch at path: #{path}"
if expected.class == Hash
expect(actual.keys).to match_array(expected.keys), "Keys mismatch at path: #{path}"
expected.keys.each do |key|
expect_json_eq(actual[key], expected[key], "#{path}/:#{key}")
end
elsif expected.class == Array
expected.each_with_index do |e, index|
expect_json_eq(actual[index], expected[index], "#{path}[#{index}]")
end
else
expect(actual).to eq(expected), "Type #{expected.class} expected #{expected.inspect} but got #{actual.inspect} at path: #{path}"
end
end
用法示例1:
expect_response(response, :no_content)
用法示例2:
expect_response(response, :ok, {
story: {
id: 1,
name: "Shire Burning",
revisions: [ ... ],
}
})
输出示例:
Type String expected "Shire Burning" but got "Shire Burnin" at path: /:story/:name
另一个示例输出展示了嵌套数组深处的不匹配:
Type Integer expected 2 but got 1 at path: /:story/:revisions[0]/:version
如您所见,输出将告诉您确切的位置来修复期望的JSON。