Skip to content

Intermittent NetConnectNotAllowedError because stub_requests unexpectedly empty #1100

Description

@dan-jensen

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?

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions