简体   繁体   English

rspec:验证序列化程序的关联

[英]rspec: validate association for serializers

# model
class Post < ActiveRecord::Base
  has_many :comments
end

# model spec
RSpec.describe Post, type: :model do
  subject { build(:post) }
  it { is_expected.to have_many(:comments) }
end

The above is the test case to validate the has_many association for model. 以上是验证模型的has_many关联的测试用例。 Similarly, is there any option to validate the same for Serializer?. 同样,是否有任何选项可以为Serializer验证相同的内容?

# serializer
class PostSerializer < ActiveModel::Serializer
  has_many :comments
end

# serializer spec
RSpec.describe PostSerializer, type: :serializer do
  let(:serializer) { PostSerializer.new(create(:post)) }

  # validation for `has_many` association.
end

I don't think there are RSpec matchers for active_model_serializers which is a separate third-party gem. 我不认为有针对active_model_serializers RSpec匹配器,它是一个单独的第三方gem。 Your best bet is to use the serializer to generate a hash with as_json and compare the result it in your tests. 您最好的选择是使用序列化程序生成带有as_json的哈希值,并将其结果与测试结果进行比较。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM