我有一个ActiveModel :: Serializer类(类TaskSerializer< ActiveModel :: Serializer),我正在测试。
序列化程序使用current_user对象,因为它在控制器操作期间处于范围内。
但我正在尝试编写一个新的rspec文件。 (task_serializer_spec.rb)
当我跑步时
TaskSerializer.new(task).to_json
我收到一条错误消息,指出current_user方法不存在。
我无法模拟变量,因为我们的模拟中有“方法必须存在”的标志。
我知道我可以在NEW中传递一些其他参数。但我找不到任何文件。有人可以提供一种方法来获取范围内的current_user。
1 个答案:
答案 0 :(得分:3)
My answer might be a little late, but if someone ever ends up on this page, here is a way to do this:
app/serializers/task_serializer.rb :
class TaskSerializer < ActiveModel::Serializer
attributes :id, :method_using_current_user, :whatever_other_attributes_goes_here
delegate :current_user, to: :scope
def method_using_current_user
current_user.some_method_here
end
end
In your rspec test, you can than do something like this:
RSpec.describe TaskSerializer do
let(:user) { create(:user) }
# or any other user you want to create here
before do
# As current user is delegated to controller scope, we mock both here
allow_any_instance_of(TaskSerializer).to receive(:scope).and_return(ApplicationController.new)
allow_any_instance_of(ApplicationController).to receive(:current_user).and_return(user)
end
# your test goes here
end
And voila.