mr_muscle
mr_muscle

Reputation: 2900

RSpec different DateTime format in response than passed attribute

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 ?

Upvotes: 2

Views: 1741

Answers (1)

Pavel Mikhailyuk
Pavel Mikhailyuk

Reputation: 2877

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,
      }
    }
  ],
}

Upvotes: 1

Related Questions