Skip to content

Commit

Permalink
Merge pull request #908 from adam-harwood/master
Browse files Browse the repository at this point in the history
Make global stubs thread-safe
  • Loading branch information
bblimke committed Oct 12, 2020
2 parents 7b5023d + f7a1beb commit d03e76a
Showing 1 changed file with 12 additions and 2 deletions.
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

0 comments on commit d03e76a

Please sign in to comment.