在Heroku流水线中使用无头Chrome运行Rails系统测试的正确方法
解决Heroku测试环境运行Rails系统测试找不到Chrome的问题
问题背景
推送代码到GitHub main分支触发Heroku测试环境构建后,执行bin/rails test:system时报错:
/app/vendor/bundle/ruby/3.1.0/gems/webdrivers-5.2.0/lib/webdrivers/chrome_finder.rb:21:in `location': Failed to determine Chrome binary location. (Webdrivers::BrowserNotFound)
已添加Chrome相关Buildpack,但问题依然存在。
解决方案
1. 调整Buildpack执行顺序
Buildpack的执行顺序会影响依赖加载逻辑,需将Chrome相关Buildpack放在Ruby Buildpack之前,确保Chrome在Ruby依赖安装前完成部署。修改app.json的buildpacks顺序:
{ "buildpacks": [ { "url": "https://github.com/heroku/heroku-buildpack-google-chrome" }, { "url": "https://github.com/heroku/heroku-buildpack-chromedriver" }, { "url": "heroku/ruby" } ], "environments": { "test": { "addons": ["heroku-postgresql:in-dyno"], "scripts": { "test": "bin/rails test:system" } } } }
2. 配置系统测试使用无头Chrome并指定二进制路径
在Rails系统测试配置文件(通常为test/application_system_test_case.rb)中,明确指定无头Chrome的运行参数和二进制文件路径:
require "test_helper" class ApplicationSystemTestCase < ActionDispatch::SystemTestCase driven_by :selenium, using: :chrome, screen_size: [1400, 1400] do |options| options.browser = :headless_chrome # 适配Heroku环境的必要参数 options.add_argument("--no-sandbox") options.add_argument("--disable-dev-shm-usage") # 指定Heroku上Chrome的固定安装路径 options.binary = "/app/.apt/usr/bin/google-chrome" end end
3. 设置环境变量指定Chrome路径(可选)
如果依赖webdrivers gem,可通过环境变量直接指定Chrome二进制路径,在app.json的测试环境中添加:
"environments": { "test": { "addons": ["heroku-postgresql:in-dyno"], "env": { "CHROME_BIN": "/app/.apt/usr/bin/google-chrome", "WEBDRIVERS_CHROME_PATH": "/app/.apt/usr/bin/google-chrome" }, "scripts": { "test": "bin/rails test:system" } } }
验证步骤
修改配置后重新推送代码到main分支,触发Heroku测试环境构建,检查系统测试是否正常执行。
内容的提问来源于stack exchange,提问作者Kevin W.
相关产品推荐
相关产品推荐

