Problem
My Rspec test suite occasionally encounters WebMock::NetConnectNotAllowedError because StubRegistry cannot find any stubs (when multiple were declared before(:each).
Details
We're stubbing external services as described by Thoughtbot. In other words, we're doing this:
RSpec.configure do |config|
config.before(:each) do
stub_request(:any, /api.github.com/).to_rack(FakeGitHub)
end
end
However, we see intermittent test failures randomly in our test suite because of WebMock::NetConnectNotAllowedError. After digging, we've found the problem is because in StubRegistry#request_stub_for, there are no stubs (both global_stubs and request_stubs are empty).
Some things we've learned that support the theory of a race condition:
- We monkey-patched
StubRegistry#response_for_request to re-try finding a stub (by calling request_stub_for a second time if there's no stub the first time). Sometimes it succeeds in finding a stub on the second attempt.
- Using
config.prepend_before(:each) seems to mitigate the problem.
Question
Given that we're calling stub_request in a before(:each) block, how is it possible for request_stubs to ever be empty? Or from another perspective, what could possibly be causing a race condition?
Problem
My Rspec test suite occasionally encounters
WebMock::NetConnectNotAllowedErrorbecauseStubRegistrycannot find any stubs (when multiple were declaredbefore(:each).Details
We're stubbing external services as described by Thoughtbot. In other words, we're doing this:
However, we see intermittent test failures randomly in our test suite because of
WebMock::NetConnectNotAllowedError. After digging, we've found the problem is because inStubRegistry#request_stub_for, there are no stubs (bothglobal_stubsandrequest_stubsare empty).Some things we've learned that support the theory of a race condition:
StubRegistry#response_for_requestto re-try finding a stub (by callingrequest_stub_fora second time if there's no stub the first time). Sometimes it succeeds in finding a stub on the second attempt.config.prepend_before(:each)seems to mitigate the problem.Question
Given that we're calling
stub_requestin abefore(:each)block, how is it possible forrequest_stubsto ever be empty? Or from another perspective, what could possibly be causing a race condition?