Read more

RSpec: How to compare ISO 8601 time strings with milliseconds

Emanuel De
January 31, 2023Software engineer at makandra GmbH

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

#=> "2001-01-01T00:00:00.000+00:00"
Illustration web development

Do you need DevOps-experts?

Your development team has a full backlog? No time for infrastructure architecture? Our DevOps team is ready to support you!

  • We build reliable cloud solutions with Infrastructure as code
  • We are experts in security, Linux and databases
  • We support your dev team to perform
Read more Show 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)

Otherwise the strings do not match:

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

#=> "2001-01-01T00:00:00+00:00"

#=> "2001-01-01T00:00:00.000+00:00"
Posted by Emanuel De to makandra dev (2023-01-31 10:38)