Cucumber+Capybara+Ruby自动化如何配置Chrome无头模式运行
问题排查结果
你当前配置无法触发无头模式的核心原因有3个:
- 执行cucumber命令时没有传入
BROWSER=chrome_headless环境变量,代码中无头分支根本不会执行,默认加载的是带GUI的Chrome - 你用的
desired_capabilities+chromeOptions配置写法是Selenium 3时代的旧语法,在Selenium 4 + 新版ChromeDriver中已经失效,即使传了环境变量也可能无法正确加载无头参数 - 配置块中在驱动未完成初始化时就强制调用窗口resize接口,容易引发驱动加载异常
- 现有helper.rb的截图方法存在语法错误、未定义变量问题,运行时会直接抛异常中断用例
修正后的可运行配置
1. 替换env.rb内容
require_relative 'helper.rb' require 'selenium/webdriver' require 'fileutils' World(Helper) # 默认优先读环境变量,未指定时默认走无头模式 BROWSER = ENV.fetch('BROWSER', 'chrome_headless') Capybara.register_driver :selenium do |app| chrome_options = Selenium::WebDriver::Chrome::Options.new case BROWSER when 'chrome_headless' # Chrome 112+ 版本推荐使用--headless=new,兼容所有浏览器新特性 chrome_options.add_argument('--headless=new') chrome_options.add_argument('--window-size=1440,768') chrome_options.add_argument('--disable-gpu') chrome_options.add_argument('--no-sandbox') chrome_options.add_argument('--disable-dev-shm-usage') Capybara::Selenium::Driver.new(app, browser: :chrome, options: chrome_options) when 'chrome' Capybara::Selenium::Driver.new(app, browser: :chrome, options: chrome_options) else raise "Unsupported browser type: #{BROWSER}" end end Capybara.configure do |config| config.default_driver = :selenium config.javascript_driver = :selenium config.default_max_wait_time = 60 end
2. 修复helper.rb的错误
原代码存在方法名带空格、变量未定义、目录不存在报错的问题,替换为以下内容:
module Helper def take_picture(file_name, res) file_path = "reports/screenshot/" FileUtils.mkdir_p(file_path) # 自动创建截图目录,避免首次运行报错 date_str = DateTime.now.strftime("%Y%m%d%H%M%S") picture_path = "#{file_path}#{date_str}_#{file_name}-#{res}.png" page.save_screenshot(picture_path) shot = Base64.encode64(File.open(picture_path, "rb").read) attach(shot, 'image/png') end end
正确执行命令
无头模式运行指定标签用例时,必须显式传入环境变量(如果已经把默认值设为chrome_headless可以不传):
BROWSER=chrome_headless cucumber -t@criarClienteCompraLojaClone
需要启动带GUI的浏览器调试时,执行:
BROWSER=chrome cucumber -t@criarClienteCompraLojaClone
注意事项
- 请确保本地Chrome、ChromeDriver、selenium-webdriver、capybara的大版本号保持一致,避免版本兼容问题
- 如果是在CI/Docker环境运行,不要删除
--no-sandbox和--disable-dev-shm-usage两个启动参数,否则Chrome会启动失败 - 不要在步骤定义中写固定
sleep等待,优先使用Capybara内置的元素等待逻辑,提升用例稳定性
内容的提问来源于stack exchange,提问作者Mateus Vitorino
相关产品推荐
相关产品推荐

