Enforce Webmock stub_request to raise at the end of a test if it has not been called

1.1k views Asked by At

We have a RoR application, Rspec for tests with Webmock for HTTP requests. After having to do some refactoring in our legacy codebase, I realized that many of our tests had unnecessary stubs. Like this example, the do_a function has been refactored so that we don't do any api call so the stub_request is not necessary anymore, worse, it should be removed.

    it 'does something' do
       stub_request(:get, 'http://something.com/users/123')

       do_a

       expect(..) 
    end

One way of fixing this is:

    it 'does something' do
       stub_something = stub_request(:get, 'http://something.com/users/123')

       do_a

       expect(..) 
       expect(stub_something).to have_been_requested.once
    end

But I'd like to enforce this directly through a strict mode where the test fails if any declared stub has not been called ? The first example would then fail automatically.

Thanks a lot for your help

1

There are 1 answers

2
max On

You want to use expectations instead of stub_request:

expect(WebMock).to have_requested(:get, "http://something.com/users/123").once

# or 

expect(a_request(:get, "http://something.com/users/123")).to have_been_made.once

But I'd like to enforce this directly through a strict mode where the test fails if any declared stub has not been called?

I don't think this is really possible unless you do some heavy monkeypatching - and it seems like a bad idea instead of just refactoring your tests.