我想取消对 3rd 方组件的调用,但在 Rails 迷你测试中发现这非常具有挑战性。我将从上面最基本的问题开始。这是一些非常简化的伪代码,可以更好地解释我正在尝试做的事情:
class RequestController < ActionController::Base
def schedule
# Parse a bunch of params and validate
# Generate a unique RequestId for this request
# Save Request stuff in the DB
# Call 3rd party scheduler app to queue request action
scheduler = Scheduler.new
submit_success = scheduler.submit_request
# Respond to caller
end
end
所以我正在为 RequestController 编写集成测试,并且我想删除“scheduler.submit_request”调用。我的测试代码如下所示:
def test_schedule_request
scheduler_response = 'Expected response string for RequestId X'
response = nil
Scheduler.stub :submit_request, scheduler_response do
# This test method calls the RequestController schedule route above
response = send_schedule_request(TEST_DATA)
end
# Validate (assert) response
end
看起来很简单,但显然我不能为一个不存在的类(还)存根一个方法。那么如何在我正在测试的代码中为运行时创建的对象存根类方法呢?