在rspec测试中找不到stubbed方法

时间:2015-05-27 15:47:29

标签: ruby-on-rails-4 rspec3

在我的控制器中,我的代码就像......

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

任何想法为什么?感谢。

1 个答案:

答案 0 :(得分:0)

执行代码行时

expect_any_instance sets the expectation。它不会验证对spy的期望。

在测试代码运行后,您正在设置期望值。将期望定义向上移动一行:

 expect_any_instance_of(JobApplication).to receive(:apply_for_job)

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