Search code examples
ruby-on-railsrubyrspecrspec-rails

Test datetime fields as a JSON string using rspec


I'm trying to test a JSON response with rspec (in Rails) by equality between [the original object].to_json and the response body. The problem is that the updated_at and created_at fields in the response JSON string are different than the same fields in the original object by milliseconds and therefore the test failed.

The test:

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

The result:

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\"}"

Note that the two strings are equal, except the 870 milliseconds in the expectation (and 000 in the actual result).

How can I test that?


Solution

  • I would parse JSON response JSON.parse(response.body) and verified that:

    1) lesson.attributes.keys contains exactly the same keys as in the parsed JSON;

    2) checked that each value except created_at and updated_at matches to the appropriate key value from the parsed JSON.

    3) If you want you can test created_at and updated_at for presence as well.