【问题标题】:How to fix 'json atom at path "name" is missing'?如何修复'路径“名称”处的json原子丢失'?
【发布时间】:2019-12-17 06:39:12
【问题描述】:

我正在为我的应用程序做一个序列化程序,我需要对其进行测试,但是当我运行规范时,它总是返回“路径“名称”处的 json atom is missing”。我正在使用 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

【问题讨论】:

    标签: ruby-on-rails json ruby api serialization


    【解决方案1】:

    我想通了!

    通过使用 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,
              }
            }
          )
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-11-30
      • 2019-12-23
      • 1970-01-01
      • 1970-01-01
      • 2014-09-01
      • 1970-01-01
      • 2020-03-14
      • 1970-01-01
      相关资源
      最近更新 更多