You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用RSpec测试Rails中的Fast JSON API?序列化测试报错求助

解决Fast JSON API序列化器的RSpec测试报错问题

你遇到的这个报错是因为Fast JSON API严格遵循JSON:API规范,这个规范要求每个序列化的资源必须包含id字段,而你传入的测试数据用的是_id,不符合要求,所以抛出了FastJsonapi::MandatoryField错误。另外还有个小问题:你直接调用result.name是不对的,因为serialized_json返回的是JSON字符串,不是Ruby对象,得先解析成哈希才能取值。

下面给你两种解决思路,根据你的实际场景选择:

方案一:调整测试数据,使用规范的id字段

如果你的模型本身用的是标准的id作为主键,那直接把测试数据里的_id改成id就行,同时修正测试断言的方式:

require 'rails_helper'
describe 'UserSerializer' do
  it 'serializes the name field correctly' do
    # 用标准的id字段替代_id
    test_user = {id: "1ew345", name: 'kdlls'}
    # 把序列化后的JSON字符串解析成Ruby哈希
    serialized_result = JSON.parse(UserSerializer.new(test_user).serialized_json)
    
    # 按照JSON:API的结构取值:data -> attributes -> name
    expect(serialized_result['data']['attributes']['name']).to eq('kdlls')
    # 顺便验证id也被正确序列化了
    expect(serialized_result['data']['id']).to eq("1ew345")
  end
end

方案二:如果模型用的是_id作为主键(比如MongoDB场景)

如果你的User模型确实用_id作为主键(比如用MongoDB的时候),可以在序列化器里指定id字段的来源,让它映射到_id属性:

首先修改序列化器:

class UserSerializer
  include FastJsonapi::ObjectSerializer
  # 告诉序列化器,用模型的_id属性作为JSON:API规范里的id字段
  set_id :_id
  attributes :name
end

然后对应的测试代码可以保留_id,但还是要记得解析JSON字符串:

require 'rails_helper'
describe 'UserSerializer' do
  it 'serializes correctly with custom _id as primary key' do
    test_user = {_id: "1ew345", name: 'kdlls'}
    serialized_result = JSON.parse(UserSerializer.new(test_user).serialized_json)
    
    expect(serialized_result['data']['attributes']['name']).to eq('kdlls')
    # 这里的id会映射到我们的_id值
    expect(serialized_result['data']['id']).to eq("1ew345")
  end
end

最后再提醒一下:JSON:API的响应结构是固定的,所有资源数据都在data对象里,属性放在attributes下,所以测试的时候一定要按照这个层级来断言,不要直接去取顶级的name哦~

内容的提问来源于stack exchange,提问作者Davi Luis

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.14 08:34:48