RSpec different DateTime format in response than passed attribute

Viewed 654

I want to test if response is serialized in a proper way (I'm using Fast JSON API serializer). To do so I've create a sample response which I want to compare:

let!(:journey_progress) { create(:journey_progress, started_at: current_date) }

let(:current_date) { 'Thu, 16 Jul 2020 17:08:02 +0200' }

let(:serializer_response) do
{
  'data' => [
    {
      'id' => 1,
      'type' => 'percent_progress',
      'attributes' => {
        'percent_progress' => 0.5,
        'started_at' => current_date,
      }
    }
  ],
}
end

it 'serializes journey with proper serializer' do
  call
  expect(JSON.parse(response.body)).to eq(serializer_response)
end

In the response I'm getting:

-"data" => [{"attributes"=>{"percent_progress"=>0.5, "started_at"=>"Thu, 16 Jul 2020 17:08:02 +0200"}],
+"data" => [{"attributes"=>{"percent_progress"=>0.5, "started_at"=>"2020-07-16T15:08:02.000Z"}],

What is this 2020-07-16T15:08:02.000Z format and why it's not in the same format which I passed to created journey_progress object ?

1 Answers

Rails uses ISO 8601 as default format of JSON serialization for Time objects.

Also, it's better not to rely on ActiveRecord time parsing and use same Time object either for the expectation and for creating the record:

let(:current_date) { Time.parse('Thu, 16 Jul 2020 17:08:02 +0200') }

let(:serializer_response) do
{
  'data' => [
    {
      'id' => 1,
      'type' => 'percent_progress',
      'attributes' => {
        'percent_progress' => 0.5,
        'started_at' => current_date.utc.as_json,
      }
    }
  ],
}
Related