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。