ruby-on-rails – 活动模型序列化器,测试使用哪个序列化器来呈现响应

前端之家收集整理的这篇文章主要介绍了ruby-on-rails – 活动模型序列化器,测试使用哪个序列化器来呈现响应前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我正在使用活动模型序列化程序来呈现来自rails控制器的 JSON响应.

我有这样的控制器动作:

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控制器测试中使用了哪个序列化器.是否有可能从测试中获得对序列化器的引用?

更新:

我不认为这是正确使用序列化器.我现在在序列化程序本身中有逻辑来有条件地包含属性.控制器不应该真正关心使用哪个序列化器.

解决方法

你可以试试这个.我假设你正在使用factory_girl.您可以通过为current_user返回不同的用户来编写其他测试
describe "show" do
  it "should use FooSerializer to serialize if the logged in user is the same as params user" do
    user = FactoryGirl.create(:user)
    controller.stub(:current_user).and_return(user)
    FooSerializer.any_instance.should_receive(:to_json).and_return("{\"key\": \"value\"")
    get :show,:id => user.id
    response.should be_success
  end
end
原文链接:https://www.f2er.com/ruby/269044.html

猜你在找的Ruby相关文章