0

Let's say there's a method report defined on ErrorReporter module. In my RSpec test suite I'd like to somehow globally stub this method so that test fails if it's not explicitly expected to receive this message.

For instance, this test

expect "responds with HTTP 200 OK" do
  perform_request # calls ErrorReporter.report somewhere

  expect(response).to have_http_status(:ok)
end

should fail if perform_request invokes ErrorReporter.report.

And this test

expect "responds with HTTP 200 OK" do
  perform_request # calls ErrorReporter.report somewhere

  expect(response).to have_http_status(:ok)
  expect(ErrorReporter).to have_received(:report).with(...).once # explicit expectation
end

does not fail because we defined explicit have_received expectation.

I want something like this:

# spec_helper.rb

config.before(:each) do
  allow(ErrorReporter).to receive(:report).and_return(true)
end

config.after(:each) do
  expect(ErrorReporter).not_to have_received(:report) # disallow by default
end

but it fails with error "ErrorReporter expected to have received report, but that method has been mocked instead of stubbed or spied."

2
  • 1
    Does just adding expect(ErrorReporter).to recieve(:report).never to the before block work? Commented Nov 12 at 21:58
  • 1
    You're looking for allow(ErrorReporter).to receive(:report).and_call_original in your last attempt
    – BroiSatse
    Commented Nov 12 at 23:51

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Browse other questions tagged or ask your own question.