RSpec 响应中的日期时间格式与传递的属性不同

RSpec different DateTime format in response than passed attribute

我想测试响应是否以正确的方式序列化(我正在使用快速 JSON API 序列化程序)。为此,我创建了一个我想比较的示例响应:

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

在我得到的回复中:

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

这是什么 2020-07-16T15:08:02.000Z 格式,为什么它与我传递给创建的 journey_progress 对象的格式不同?

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

此外,最好不要依赖 ActiveRecord 时间解析并使用相同的 Time 对象来进行期望和创建记录:

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