Rails执行系统测试报错Webdrivers::BrowserNotFound 找不到Chrome binary
错误原因
Webdrivers::BrowserNotFound: Failed to find Chrome binary 报错的直接原因是Rails系统测试依赖的webdrivers gem无法在你的系统中找到Chrome/Chromium浏览器的可执行文件。
解决步骤
步骤1:安装Chrome/Chromium浏览器
根据你的操作系统安装对应版本:
- Debian/Ubuntu系列:执行命令
sudo apt install chromium-browser chromium-chromedriver - Fedora/RHEL系列:执行命令
sudo dnf install chromium chromium-chromedriver - macOS:直接下载安装Chrome官方版本,或通过Homebrew执行
brew install --cask google-chrome - Windows:下载安装Chrome官方版本,将Chrome安装路径添加到系统环境变量PATH中
步骤2:手动指定浏览器路径(安装后仍报错时使用)
如果已经安装浏览器但仍无法识别,需要在系统测试配置文件中手动指定二进制文件路径。
找到报错中提到的 test/application_system_test_case.rb 文件,修改驱动配置:
require "test_helper" class ApplicationSystemTestCase < ActionDispatch::SystemTestCase # 配置Chrome驱动 driven_by :selenium, using: :chrome, screen_size: [1400, 1400] do |options| # 开启无头模式,无需弹出浏览器窗口,测试速度更快也不需要图形环境 options.add_argument('--headless=new') # 替换为你系统中Chrome/Chromium的实际路径,可通过 which chromium-browser 或者 which google-chrome 命令查看 options.binary = '/usr/bin/chromium-browser' end end
你也可以在 test_helper.rb 中添加配置指定webdrivers的查找路径:
# 放在 require 'webdrivers' 代码行之后 Webdrivers::Chrome.binary = '/usr/bin/chromium-browser' # 替换为实际路径
步骤3:版本适配校验
如果仍报错,大概率是Chrome浏览器和chromedriver版本不匹配,执行以下操作:
- 更新Chrome/Chromium到最新稳定版
- 执行
bundle update webdrivers升级webdrivers gem到最新版本,它会自动下载匹配当前浏览器版本的chromedriver
额外注意事项(浏览器问题解决后可能遇到的测试报错)
- 你的items测试中
assert_selector "h1", text: "Items"与index页面实际的h1文本Item Index不匹配,需要修改其中一方保持一致 - index页面的Create Item按钮跳转路径是
/add,需要确保路由配置中将/add映射到items#new动作,否则点击后会返回404错误 - 系统测试默认不支持
assert_template方法,需要在测试类中添加include ActionController::TemplateAssertions兼容,或者改用断言页面元素的方式验证是否跳转到新建页面
内容的提问来源于stack exchange,提问作者Omari Wilson
相关产品推荐
相关产品推荐

