Ruby on rails test ActiveModel::具有变量而不使用控制器测试仪的序列化程序
我有一个要测试的ActiveModel::Serializer类TaskSerializerRuby on rails test ActiveModel::具有变量而不使用控制器测试仪的序列化程序,ruby-on-rails,rspec,Ruby On Rails,Rspec,我有一个要测试的ActiveModel::Serializer类TaskSerializer
TaskSerializer.new(task).to_json
我得到一个错误,说当前的用户方法不存在
我无法模拟该变量,因为我们在模拟上有“方法必须存在”标志
我知道还有一些其他的参数可以在新版本中传递。但是我在上面找不到任何文件。是否有人能提供一种方法来获取范围内的当前用户之类的内容 我的回答可能有点晚了,但如果有人出现在这一页上,下面是一种方法: 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
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