Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 388
Lidan Avatar asked Oct 01 '13 22:10

Lidan


2 Answers

I've accomplished this in a better way by comparing the datetime from the json response to my object's datetime_field.as_json:

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

    # ... other fields
  }
}
like image 160
Rafael Garcia Avatar answered Oct 03 '22 07:10

Rafael Garcia


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.

like image 42
Nikita Chernov Avatar answered Oct 03 '22 06:10

Nikita Chernov