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 money motivation

Opscomplete powered by makandra brand

Save money by migrating from AWS to our fully managed hosting in Germany.

  • Trusted by over 100 customers
  • Ready to use with Ruby, Node.js, PHP
  • Proactive management by operations experts
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)