给定以下ActiveModel :: Serializer类:
class SampleSerializer < ActiveModel::Serializer attributes :id,:name end
如何用RSpec进行测试?
解决方法
假设
这个答案假定您已经安装并配置了rspec-rails,active_model_serializers和factory_girl_rails gem.
此答案还假设您已为Sample资源定义了一个工厂.
串行器规格
对于写入时active_model_serializers的当前版本(0.10.0.rc3),ActiveModel :: Serializer类不会收到to_json,而是包装在适配器类中.要获得包装在序列化器实例中的模型的序列化,必须创建适配器的实例:
before(:each) do # Create an instance of the model @sample = FactoryGirl.build(:sample) # Create a serializer instance @serializer = SampleSerializer.new(@sample) # Create a serialization based on the configured adapter @serialization = ActiveModel::Serializer::Adapter.create(@serializer) end
适配器实例接收to_json方法并返回模型的序列化.
subject { JSON.parse(@serialization.to_json) }
然后可以在返回的JSON上运行期望.
it 'should have a name that matches' do expect(subject['name']) .to eql(@sample.name) end
解析JSON响应时,必须考虑适配器配置:
>默认的config,:attributes可以生成没有根密钥的JSON响应:
subject { JSON.parse(@serialization.to_json) }
>:json config根据模型的名称生成带有根键的JSON响应:
subject { JSON.parse(@serialization.to_json)['sample'] }
>:json_api config生成符合jsonapi标准的JSON:
subject { JSON.parse(@serialization.to_json)['data']['attributes'] }