RSpec: How to compare ISO 8601 time strings with milliseconds

Posted Over 1 year ago. Visible to the public.

Rails includes milliseconds in Time / DateTime objects when rendering them as JSON:

JSON.parse(User.last.to_json)['created_at']
#=> "2001-01-01T00:00:00.000+00:00"

In RSpec you might want to use .to_json instead of .iso8601 to use the build-in eq matcher:

it 'returns the created at attribute of a user' do
  get '/users/1'
  
  expect(JSON.parse(response.body)['created_at']).to eq(Time.parse('2001-01-01').to_json)
end

Otherwise the strings do not match:

DateTime.parse('2001-01-01').to_s (will default to iso8601)
#=> "2001-01-01T00:00:00+00:00"

DateTime.parse('2001-01-01').iso8601
#=> "2001-01-01T00:00:00+00:00"

DateTime.parse('2001-01-01').to_json
#=> "2001-01-01T00:00:00.000+00:00"
Last edit
Over 1 year ago
Emanuel
License
Source code in this card is licensed under the MIT License.
Posted by Emanuel to makandra dev (2023-01-31 09:38)