如何使用 mocha 在 Rails 控制器中模拟 类

How to mock classes in Rails controller with mocha

我很难理解如何在 Rails 中使用 mocha 模拟库进行某些类型的单元测试。

我有一个控制器,它从辅助库中初始化一个对象,然后在其上调用一个函数。我的代码看起来类似于

class ObjectsController < ApplicationController
  before_action :set_adapter

  def index
    response = @adapter.get_objects

    render json: response
  end

  private
    def set_adapter
      arg = request.headers["X-ARG"]
      @adapter = Adapter::Adapter.new(arg)
    end
end

在我的测试中,我想模拟适配器以确保调用 get_objects() 方法。我试图弄清楚什么是实现这种测试的最佳方法,但我似乎一直在思考如何在 class.

中模拟现有对象。

谁能帮帮我?

你可以像这样存根:

adapters = mock('object')
adapters.expects(:get_objects)
Adapter::Adapter.expects(:new).with('<X-ARG-HEADER-HERE>').returns(adapters)
# Run rest of test here to trigger calling the index method

希望对您有所帮助。