Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Make global stubs thread-safe #908

Merged
merged 1 commit into from Oct 12, 2020
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
14 changes: 12 additions & 2 deletions lib/webmock/stub_registry.rb
Expand Up @@ -23,10 +23,20 @@ def register_global_stub(&block)
# That way, there's no race condition in case #to_return
# doesn't run immediately after stub.with.
responses = {}
response_lock = Mutex.new

stub = ::WebMock::RequestStub.new(:any, ->(uri) { true }).with { |request|
responses[request.object_id] = yield(request)
}.to_return(lambda { |request| responses.delete(request.object_id) })
update_response = -> { responses[request.object_id] = yield(request) }

# The block can recurse, so only lock if we don't already own it
if response_lock.owned?
update_response.call
else
response_lock.synchronize(&update_response)
end
}.to_return(lambda { |request|
response_lock.synchronize { responses.delete(request.object_id) }
})

global_stubs.push stub
end
Expand Down