You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Capybara测试触发意外Google HTTP请求的配置问题排查

问题

在Rails 7应用中,我有一个带Turbo异步提交的单页Web表单,编写了如下Capybara特性测试:

context 'when the user enters a valid params', js: true do
  it 'renders the image after async form submision' do
    breed = Faker::Creature::Dog.breed

    visit root_path
    fill_in 'breed', with: breed

    click_button 'Submit'

    expect(page).to have_css("turbo-frame[id='dog-image']")
  end
end

运行测试时触发以下错误:

WebMock::NetConnectNotAllowedError:
  Real HTTP connections are disabled. Unregistered request: GET https://googlechromelabs.github.io/chrome-for-testing/latest-patch-versions-per-build.json with headers {'Accept'=>'*/*', 'Accept-Encoding'=>'gzip;q=1.0,deflate;q=0.6,identity;q=0.3', 'Host'=>'googlechromelabs.github.io', 'User-Agent'=>'Ruby'}

我的spec_helper.rb配置已允许localhost请求:

require 'capybara/rspec'
require 'rails_helper'
require 'webmock/rspec'
require 'selenium-webdriver'

Capybara.register_driver :chrome do |app|
  Capybara::Selenium::Driver.new(app, browser: :chrome)
end

Capybara.javascript_driver = :chrome

RSpec.configure do |config|
  config.expect_with :rspec do |expectations|
    expectations.include_chain_clauses_in_custom_matcher_descriptions = true
  end
  config.mock_with :rspec do |mocks|
    mocks.verify_partial_doubles = true
  end
  config.shared_context_metadata_behavior = :apply_to_host_groups
  
  WebMock.disable_net_connect! allow_localhost: true
  Capybara.server = :puma, { Silent: true }
  Capybara.javascript_driver = :selenium_chrome_headless
  Capybara.default_max_wait_time = 5
  Capybara.server_host = 'localhost'
  Capybara.server_port = 3000
  Capybara.app_host = 'http://localhost'
end

设置WebMock.allow_net_connect!能让测试通过,但这不是最佳实践,请问配置里遗漏了什么?

解决方案

这个错误是因为Selenium ChromeDriver在自动检测Chrome版本时,会发起对googlechromelabs.github.io的请求,而WebMock默认拦截了所有非localhost的外部请求。

有两种可行的解决方式:

1. 允许ChromeDriver相关域名的请求

在WebMock配置中,将googlechromelabs.github.io加入允许列表:

WebMock.disable_net_connect! allow_localhost: true, allow: 'googlechromelabs.github.io'

2. 指定ChromeDriver路径,跳过版本检测

如果不想让测试依赖外部请求,可以手动指定ChromeDriver的路径,避免自动版本检测:

Capybara.register_driver :selenium_chrome_headless do |app|
  options = Selenium::WebDriver::Chrome::Options.new(args: %w[headless no-sandbox disable-gpu])
  driver_path = '/path/to/your/chromedriver' # 替换为实际的ChromeDriver路径
  Capybara::Selenium::Driver.new(app, browser: :chrome, options: options, driver_path: driver_path)
end

另外注意你的配置中重复设置了Capybara.javascript_driver,先设为:chrome又改成:selenium_chrome_headless,建议统一保留后者即可,避免配置冲突。

内容的提问来源于stack exchange,提问作者mr_muscle

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.09 00:40:05