1

我想取消对 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

看起来很简单,但显然我不能为一个不存在的类(还)存根一个方法。那么如何在我正在测试的代码中为运行时创建的对象存根类方法呢?

4

2 回答 2

1

我不确定minitest。但是在 rspec 中,您还必须对初始化部分进行存根并返回一个模拟的调度程序对象

这就是我在 rspec 中的做法。

mock_scheduler = double("scheduler")
Scheduler.stub(:new).and_return(mock_scheduler)
mock_scheduler.stub(:submit_request).and_return(response)

其他选择是

   Scheduler.any_instance.stub(:submit_request).and_return(response)
于 2013-11-19T21:46:00.893 回答
0

正如 Vimsha 所指出的,您必须首先对类初始化进行存根。我无法让他的代码工作,但下面这个修改后的测试代码具有相同的想法:

def test_schedule_request
  scheduler_response = 'Expected response string for RequestId X'
  response = nil
  scheduler = Scheduler.new
  Scheduler.stub :new, scheduler do
    scheduler.stub :submit_request, scheduler_response do
      # This test method calls the RequestController schedule route above
      response = send_schedule_request(TEST_DATA)
    end
  end

  # Validate (assert) response
end

谢谢,戴夫

于 2013-11-20T22:28:52.980 回答