Module: HttpDecoy::WebMockIntegration

Defined in:
lib/http_decoy/webmock_integration.rb

Overview

Manages the WebMock stub that routes a declared base_url to the server’s Rack app.

Auto-detect: if WebMock is loaded and HttpDecoy.configuration.auto_intercept is true, requests to the declared base_url are intercepted transparently.

Teardown removes only the stub http_decoy created — never calls WebMock.reset!. If WebMock/RSpec has already cleared the registry (its own after(:each) hook), we rescue silently rather than crashing.

Class Method Summary collapse

Class Method Details

.available?Boolean

Returns:

  • (Boolean)


14
15
16
# File 'lib/http_decoy/webmock_integration.rb', line 14

def available?
  defined?(WebMock) && WebMock.respond_to?(:stub_request)
end

.setup(server) ⇒ Object

Install an interception stub for the given server. Returns the stub object so it can be removed precisely during teardown.



20
21
22
23
24
25
26
27
28
29
30
# File 'lib/http_decoy/webmock_integration.rb', line 20

def setup(server)
  return nil unless available? && HttpDecoy.configuration.auto_intercept
  return nil unless server.route_map.declared_base_url

  # Match the full base URL (scheme + host) so the regex anchors correctly.
  # e.g. "https://api.stripe.com" → /\Ahttps:\/\/api\.stripe\.com/
  base    = server.route_map.declared_base_url.chomp("/")
  pattern = /\A#{Regexp.escape(base)}/

  WebMock.stub_request(:any, pattern).to_rack(server.rack_app)
end

.teardown(stub) ⇒ Object

Remove only the stub we created. Rescues silently if webmock/rspec already cleared the registry between examples.



34
35
36
37
38
39
40
# File 'lib/http_decoy/webmock_integration.rb', line 34

def teardown(stub)
  return unless stub && available?

  WebMock::StubRegistry.instance.remove_request_stub(stub)
rescue RuntimeError
  # Already removed by WebMock.reset! (e.g. webmock/rspec after(:each) hook). Fine.
end