[英]test ActiveModel::Serializer that has a variable without using the controller tester
我有一個ActiveModel :: Serializer類(TaskSerializer <ActiveModel :: Serializer類),我正在測試。 序列化程序使用current_user對象,因為它在控制器操作期間處於作用域內。
但是我正在嘗試編寫一個新的rspec文件。 (task_serializer_spec.rb)
當我跑步
TaskSerializer.new(task).to_json
我收到一條錯誤消息,指出current_user方法不存在。
我無法模擬變量,因為在模擬中有“方法必須存在”標志。
我了解我可以在NEW中傳遞其他一些參數。 但我找不到關於它的任何文檔。 有人可以提供一種在范圍內獲取諸如current_user之類的方法的方法。
我的回答可能有點晚了,但是如果有人最終出現在此頁面上,則可以采用以下方法:
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測試中,您可以執行以下操作:
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
和瞧。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.