我正在为我的应用程序执行序列化程序,我需要对其进行测试,但是在运行规范时,它始终返回“缺少“名称”的路径处的json原子”。我正在使用FastJson来构建我的序列化程序。
我的StudentSerializer(所有属性都在“学生模型”中):
# frozen_string_literal: true
class Api::V2::StudentSerializer < ApplicationSerializer
attributes :email, :name, :school_id
end
我的StudentSerializer_Spec:
require 'rails_helper'
RSpec.describe Api::V2::StudentSerializer, type: :serializer do
subject(:serializer) { described_class.new(student) }
context 'is student serialize working?' do
let(:student) { build_stubbed(:student) }
it 'serializes' do
Api::V2:: StudentSerializer.new (student)
expect(serializer).to include_json(
name: student.name
)
end
end
end
运行rspec时,我得到的结果是:
Api::V2::StudentSerializer
is student serialize working?
serializes (FAILED - 1)
1) Api::V2::StudentSerializer is student serialize working? serializes
Failure/Error:
expect(serializer).to include_json(
name: student.name
)
json atom at path "name" is missing
答案 0 :(得分:0)
我知道了!
通过使用FastJson,Json以'data:'开头:
{:data=>
{:id=>"1",
:attributes=>
{:email=>"",
:name=>"Burdette Schmeler",
:school_id=>1}}}
所以,在我的规格文件中,我需要这样写:
context 'is student serialize working?' do
let(:student) { create(:student) }
it 'serializes' do
expect(serializer).to include_json(
data: {
id: student.id.to_s,
attributes: {
name: student.name,
email: student.email,
school_id: student.school_id,
}
}
)