webmock icon indicating copy to clipboard operation
webmock copied to clipboard

Webmock matchers and forked processes

Open kwstannard opened this issue 7 months ago • 2 comments

I think this is maybe a feature request. WebMock matchers do not work with forking. This makes sense logically given that a web request will change the stub object and trigger copy-on-write. It would be great if there was a way to have the copied stub in the fork send back the recorded requests to the main process stub though.

Ruby 3.3.3 WebMock 3.23.1

require 'webmock'
require 'webmock/rspec'

def fork_code
  3.times {
    fork do
      Net::HTTP.get(URI.parse('http://localhost'))
    end
  }
  Process.waitall
end

def thread_code
  3.times {
    Thread.new do
      Net::HTTP.get(URI.parse('http://localhost'))
    end
  }
  Process.waitall
end

# test
WebMock.enable!
WebMock.disable_net_connect!
stub = WebMock.stub_request(:get, 'localhost').and_return(body: ->(_) { printf 'Called! '; ''} )

fork_code

matcher = WebMock::RequestPatternMatcher.new.times(3)
puts "Does the main process count forked requests? #{matcher.matches?(stub)}"
puts
puts matcher.failure_message

thread_code

matcher = WebMock::RequestPatternMatcher.new.times(3)
puts "Does the main process count threaded requests? #{matcher.matches?(stub)}"
puts
puts matcher.failure_message
~ $ ruby /tmp/fork_spec.rb
Called! Called! Called! Does the main process count forked requests? false

The request GET http://localhost/ was expected to execute 3 times but it executed 0 times

The following requests were made:

No requests were made.
============================================================
Called! Called! Called! Does the main process count threaded requests? true

The request GET http://localhost/ was expected to execute 3 times but it executed 3 times

The following requests were made:

GET http://localhost/ with headers {'Accept'=>'*/*', 'Accept-Encoding'=>'gzip;q=1.0,deflate;q=0.6,identity;q=0.3', 'Host'=>'localhost', 'User-Agent'=>'Ruby'} was made 3 times

============================================================

kwstannard avatar Jul 15 '24 16:07 kwstannard