6

[the original object].to_json我正在尝试通过与响应主体之间的相等性来测试带有 rspec(在 Rails 中)的 JSON 响应。问题是响应 JSON 字符串中的updated_atandcreated_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)。

我该如何测试呢?

4

3 回答 3

4

通过比较来自 json 响应的日期时间与我的对象的日期时间,我以更好的方式完成了这一点datetime_field.as_json

expect(json_body).to eq {
  order: {
    ordered_at: order.ordered_at.as_json 

    # ... other fields
  }
}
于 2017-10-08T14:25:43.980 回答
2

我会解析 JSON 响应JSON.parse(response.body)并验证:

1)lesson.attributes.keys包含与解析的 JSON 中完全相同的键;

2) 检查每个值是否与解析后的 JSON 中的相应键值不同created_at并匹配。updated_at

3)如果你愿意,你也可以测试created_atupdated_at存在。

于 2013-10-01T22:20:25.417 回答
2

我认为这种方式要好得多:

JSON.parse(response.body).except('created_at', 'updated_at').should eq lesson.attributes.except('created_at', 'updated_at')
于 2014-05-16T02:13:23.113 回答