Let Selenium's WebDriver traffic bypass WebMock

Posted . Visible to the public.

WebMock hooks into every Net::HTTP request your tests make, including the WebDriver commands Selenium sends to chromedriver. A system spec sends hundreds of them. For each one, WebMock builds a request signature, matches it against all stubs and adds it to its request registry. In one project, profiling showed this took about 10% of the Ruby CPU time of the system and browser automation specs.

Settings like WebMock.disable_net_connect!(allow_localhost: true) or VCR's ignore_localhost don't help. They only decide what happens after WebMock has processed the request.

Selenium talks to a chromedriver on the same machine, so there is nothing to stub or record. This monkey patch lets its HTTP client use the original Net::HTTP implementation:

# spec/support/webmock.rb

# Selenium talks to chromedriver on this machine, so it bypasses WebMock (and VCR, which hooks into it).
module SeleniumHttpClientWithoutWebMock
  private

  def new_http_client
    WebMock::HttpLibAdapters::NetHttpAdapter::OriginalNetHTTP.new(server_url.host, server_url.port, nil)
  end
end

# Selenium::WebDriver::Remote::Http::Default#new_http_client is private. After an update, check that the
# patch is still called (e.g. no WebDriver requests in WebMock::RequestRegistry), then raise the version here.
if Gem::Version.new(Selenium::WebDriver::VERSION) > Gem::Version.new('4.44.0')
  raise "Please check whether SeleniumHttpClientWithoutWebMock still works with selenium-webdriver #{Selenium::WebDriver::VERSION}"
end

Selenium::WebDriver::Remote::Http::Default.prepend(SeleniumHttpClientWithoutWebMock)
Profile picture of Michael Leimstädtner
Michael Leimstädtner
Last edit
Michael Leimstädtner
License
Source code in this card is licensed under the MIT License.
Posted by Michael Leimstädtner to makandra dev (2026-11-05 13:16)