水豚 selenium_chrome 去 example.com 而不是 localhost

Capybara selenium_chrome going to example.com instead of localhost

我正在 Rails 项目中设置 Cucumber 测试。当我使用默认驱动程序时一切正常;但是,当我尝试使用 :selenium_chrome 驱动程序时,浏览器会尝试加载 example.com 而不是本地 Rails 服务器。知道我错过了什么吗?

我的步骤是这样的:

Before do |scenario|
  Capybara.current_driver = :selenium_chrome
end

When(/^I visit the posts page$/) do
  visit posts_url
end

当我 运行 功能时,我可以看到 rails 服务器已启动:

Using the default profile...
Feature: Posts

Capybara starting Puma...
* Version 3.12.0 , codename: Llamas in Pajamas
* Min threads: 0, max threads: 4
* Listening on tcp://127.0.0.1:62056

但是,弹出的 Chrome window 试图访问 http://www.example.com/posts 而不是 http://127.0.0.1:62056/posts

我是不是在某处遗漏了配置步骤?

相关说明:如果我想 运行 我所有的测试都使用 Selenium,我是否必须将 Capybara.current_driver 行放在 Before 块中?我尝试将它添加到 features/support/env.rb,但它似乎没有任何效果。

我在 MacOS 10.14.4 上安装了 Chrome 73.0.3683.86 和 Rails 5.2.2 运行ning。

您需要设置 Capybara app_host 配置,例如 Capybara.app_host = ...。查看完整文档 here

通常,您在 spec_helper.rb 中设置 Capybara 配置,以便在所有规格中启用它,例如:

Capybara.configure do |config|
  config.current_driver = :selenium_chrome
  config.app_host   = ...
end

希望这能回答您的问题?

如果要使用:selenium_chrome作为默认驱动,可以设置Capybara.default_driver = :selenium_chrome

至于 example.com 问题,那是因为您正在访问 posts_url 并且在您的测试环境中将 Rails 默认主机名设置为 example.com。您可以访问 posts_path,这将允许 Capybara 将主机名默认为 localhost - 或者更新您的测试环境配置,以便 url 助手生成您期望的 url。