【问题标题】:test ActiveModel::Serializer that has a variable without using the controller tester在不使用控制器测试器的情况下测试具有变量的 ActiveModel::Serializer
【发布时间】:2014-09-03 00:41:51
【问题描述】:

我有一个要测试的 ActiveModel::Serializer 类(TaskSerializer 类

但我正在尝试编写一个新的 rspec 文件。 (task_serializer_spec.rb)

当我跑步时

TaskSerializer.new(task).to_json

我收到一条错误消息,指出 current_user 方法不存在。

我不能模拟变量,因为我们的模拟上有“方法必须存在”标志。

我了解我可以在 NEW 中传递一些其他参数。但我找不到任何文档。有人可以提供一种在范围内获取诸如 current_user 之类的东西的方法。

【问题讨论】:

    标签: ruby-on-rails rspec


    【解决方案1】:

    我的回答可能有点晚了,但如果有人最终出现在这个页面上,这里有一种方法:

    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
    

    然后瞧。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-07-25
      • 2023-03-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-04-21
      • 1970-01-01
      相关资源
      最近更新 更多