在 rspec 测试中找不到存根方法

Stubbed method can't be found in rspec test

在我的控制器中,我有这样的代码...

def apply
  ...do some validation stuff
  jobapp = JobApplication.new
  jobapp.apply_for_job(params, job)
end

在我的测试中,我想确保在所有验证通过后,调用了 apply_for_job 方法,因此我进行了以下测试。

describe 'apply' do
    before(:each) do
      @file = Rack::Test::UploadedFile.new(Rails.root.join('spec/fixtures/files/test-resume.txt'), 'plain/text')
      allow_any_instance_of(JobApplication).to receive(:apply_for_job).and_return(true)
    end

    it 'assuming all validation passes, it calls the jobapplication apply_for_job method' do
      post :apply, file: @file, job_id: 1, format: :json
      expect_any_instance_of(JobApplication).to receive(:apply_for_job)
    end
end

当我 运行 我的测试我得到这个错误。

Failure/Error: Unable to find matching line from backtrace
Exactly one instance should have received the following message(s) but didn't: apply_for_job

知道为什么吗?谢谢

expect_any_instance sets the expectation at the time that line of code is executed. It does not verify an expectation on a spy.

您正在设置预期 在您的被测代码 之后运行。将期望定义上移一行:

 expect_any_instance_of(JobApplication).to receive(:apply_for_job)

 post :apply, file: @file, job_id: 1, format: :json