请求协助:在RSpec响应中移除created_at字段
嘿,这问题我熟,给你几个靠谱的解决办法,按需选就行:
方法1:用序列化器精准控制返回字段(推荐)
如果你的项目用了Active Model Serializers这类序列化工具,这是最规范的做法。直接在对应的用户序列化器里,只列出你想要对外返回的字段,完全不写created_at和updated_at就好:
class UserSerializer < ActiveModel::Serializer attributes :id, :email, :live, :is_confirmed, :is_pro, :user_profile, :user_settings, :subscription_end_at, :is_trialing end
之后控制器返回用户数据时,序列化器会自动帮你过滤掉没声明的字段,返回的内容里就不会出现created_at啦。
方法2:控制器里手动过滤哈希
要是你没用到序列化器,也可以在控制器层直接处理模型转成的哈希,移除不需要的字段:
def show user = User.find(params[:id]) # 用except方法剔除created_at和updated_at render json: user.as_json.except(:created_at, :updated_at) end
as_json会把ActiveRecord模型转换成Ruby哈希,except方法可以精准移除指定的键,操作起来非常直观。
方法3:测试时忽略无关字段(应急用)
如果你只是在RSpec测试里不想校验这些字段,但实际接口暂时还需要保留(不推荐长期这么干),可以用include_json匹配器只断言你关心的内容:
expect(response.body).to include_json( id: 1, email: "email1@example.com", live: true, is_confirmed: false, is_pro: false, user_profile: nil, user_settings: nil, subscription_end_at: nil, is_trialing: nil )
不过要注意,得先在Gemfile里添加rspec-json_expectations这个gem,才能用include_json这个断言方法哦。
内容的提问来源于stack exchange,提问作者shikha
相关产品推荐
相关产品推荐

