我正在使用事件模型序列化程序来呈现来自 Rails Controller 的 JSON 响应。
我有一个这样的 Controller Action :
def show
@foo = Foo.find(params[:id])
if @foo.user == current_user
render json: @foo, serializer: FooSerializer
else
render json: @foo, serializer: TrimmedFooSerializer
end
end
我希望能够测试在我的 Rspec Controller 测试中使用了哪个序列化程序。是否可以从测试中获得对序列化程序的引用?
更新:
我认为这不是序列化程序的正确使用。我现在在序列化器本身中有逻辑来有条件地包含属性。 Controller 不应该真正关心使用哪个序列化器。
最佳答案
自从有人回复以来已经有一段时间了,但如果 future 的谷歌员工发现这一点,我喜欢以下方法:
RSpec::Matchers.define :serialize_object do |object|
match do |response|
@serializer_klass.new(object).to_json == response.body
end
chain :with do |serializer_klass|
@serializer_klass = serializer_klass
end
end
然后在您的测试中,您可以执行以下操作:
expect(response).to serialize_object(claim).with(ClaimSerializer)
请注意,我没有将匹配器称为“序列化”,因为应该已经定义了该名称的匹配器。
关于ruby-on-rails - Active Model Serializer,测试使用哪个序列化器来呈现响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22098052/