我试图通过[原始对象] .to_json和响应主体之间的相等来测试rspec(在rails中)的json响应。问题是响应json字符串中的updated_at和created_at与原始对象中的相同字段不同,以毫秒为单位,因此测试失败。
测试:
lesson = FactoryGirl.create(:lesson)
request.accept = "application/json"
get :show, {:id => lesson.to_param, :location_id => lesson.location_id}, valid_session
response.body.should eq lesson.to_json
结果:
expected: "{\"id\":1,\"location_id\":1,\"day_number\":5,\"time\":\"17:00\",\"min_age\":4,\"max_age\":10,\"created_at\":\"2013-10-02T00:51:53.870+03:00\",\"updated_at\":\"2013-10-02T00:51:53.870+03:00\"}"
got: "{\"id\":1,\"location_id\":1,\"day_number\":5,\"time\":\"17:00\",\"min_age\":4,\"max_age\":10,\"created_at\":\"2013-10-02T00:51:53.000+03:00\",\"updated_at\":\"2013-10-02T00:51:53.000+03:00\"}"
请注意,两个字符串相等,但期望值为870毫秒(实际结果为000)。
我该如何测试?
谢谢!
答案 0 :(得分:3)
我会解析JSON响应JSON.parse(response.body)
并验证:
1)lesson.attributes.keys
包含与解析的JSON完全相同的密钥;
2)检查除created_at
和updated_at
之外的每个值是否与解析的JSON中的相应键值匹配。
3)如果您愿意,您也可以测试created_at
和updated_at
是否存在。
答案 1 :(得分:1)
我认为这种方式要好得多:
JSON.parse(response.body).except('created_at', 'updated_at').should eq lesson.attributes.except('created_at', 'updated_at')
答案 2 :(得分:1)
我通过将json响应中的日期时间与我的对象datetime_field.as_json
进行比较,以更好的方式完成了这项工作:
expect(json_body).to eq {
order: {
ordered_at: order.ordered_at.as_json
# ... other fields
}
}