Read more

RSpec: How to compare ISO 8601 time strings with milliseconds

Emanuel
January 31, 2023Software engineer at makandra GmbH

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"
Illustration UI/UX Design

UI/UX Design by makandra brand

We make sure that your target audience has the best possible experience with your digital product. You get:

  • Design tailored to your audience
  • Proven processes customized to your needs
  • An expert team of experienced designers
Read more Show archive.org snapshot

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"
Posted by Emanuel to makandra dev (2023-01-31 10:38)