Ben*_*bau 5 testing ruby-on-rails mocking mocha.js
我很难理解如何使用 mocha 模拟库进行 Rails 中某些类型的单元测试。
我有一个控制器,它从辅助库初始化一个对象,然后调用它的函数。我的代码看起来类似于
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
Run Code Online (Sandbox Code Playgroud)
在我的测试中,我想模拟适配器以确保调用 get_objects() 方法。我试图找出实现此类测试的最佳方法,但我似乎一直坚持如何模拟类中现有对象的想法。
谁能帮我吗?
你可以像这样存根它:
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
Run Code Online (Sandbox Code Playgroud)
希望能帮助到你。
| 归档时间: |
|
| 查看次数: |
1544 次 |
| 最近记录: |