使用 rspec 将日期时间字段测试为 JSON 字符串

Lid*_*dan 6 ruby rspec ruby-on-rails rspec-rails

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

结果:

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\"}"
Run Code Online (Sandbox Code Playgroud)

请注意,这两个字符串是相等的,除了预期中的 870 毫秒(实际结果中为 000)。

我该如何测试?

Nik*_*nov 2

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

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

2) 检查除created_at和之外的每个值是否updated_at与解析的 JSON 中的相应键值匹配。

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