我想测试响应是否以正确的方式序列化(我使用的是Fast 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作为Time对象的JSON序列化的默认格式。
此外,最好不要依赖ActiveRecord时间解析,并使用相同的时间对象来实现期望和创建记录:
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,
}
}
],
}