I setup this UserSerializer
我设置这个UserSerializer
class UserSerializer < ActiveModel::Serializer
attributes :id, :first_name, :last_name, :email, :abilities
delegate :current_user, to: :scope
delegate :current_client, to: :scope
def abilities
object.client_roles.where(client_id: current_client.id)
end
end
and this from my ApplicationController
这是我的ApplicationController。
class ApplicationController < ActionController::Base
serialization_scope :view_context
protected
def current_client
....
I put in the "delegate" code based on this railscast around 7:45
我在7:45左右根据这个railscast输入了“委托”代码
He then goes on to say that the downside is that the tests now need a view_context and gives a solution for using Test Unit.
然后他接着说,缺点是测试现在需要一个view_context,并给出了使用测试单元的解决方案。
When I run my specs I get one of two errors
当我运行我的规范时,我得到两个错误之一。
Failure/Error: get "show", :id => user.id, :format => :json NoMethodError: undefined method `current_client' for #<#:0x00000004f69f60>
失败/错误:获取“show”,:id =>用户。id:格式= >:json NoMethodError:未定义方法的current_client # < #:0 x00000004f69f60 >
or
或
Failure/Error: data.active_model_serializer.new(data, {:root => name}).to_json RuntimeError: UserSerializer#current_client delegated to scope.current_client, but scope is nil:
失败/错误:data.active_model_serializer。新(数据,{:根= >名称})。to_json RuntimeError: UserSerializer#current_client委托给范围。current_client,但范围为nil:
How do I provide the view_context in my controller specs?
如何在控制器规范中提供view_context ?
Thanks.
谢谢。
1 个解决方案
#1
3
OK. My fault. I was calling the UserSerializer
manually in my code later to do assertions. That's what was throwing the error. Fixed it just by adding:
好的。我的错。后来我在代码中手动调用UserSerializer来做断言。这就是抛出错误的原因。通过添加:
before(:each) do
UserSerializer.any_instance.stub(:scope => controller)
end
#1
3
OK. My fault. I was calling the UserSerializer
manually in my code later to do assertions. That's what was throwing the error. Fixed it just by adding:
好的。我的错。后来我在代码中手动调用UserSerializer来做断言。这就是抛出错误的原因。通过添加:
before(:each) do
UserSerializer.any_instance.stub(:scope => controller)
end