【问题标题】:Capybara selenium_chrome going to example.com instead of localhostCapybara selenium_chrome 去 example.com 而不是 localhost
【发布时间】:2019-04-03 19:59:24
【问题描述】:

我正在 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 窗口正在尝试访问 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。

【问题讨论】:

    标签: ruby-on-rails cucumber selenium-chromedriver capybara


    【解决方案1】:

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

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

    【讨论】:

    • 在这两个方面都是正确的。 default_driver vs current_driver 问题对我来说只是一个愚蠢的错误。我永远也想不出 posts_urlposts_path 的错误。
    【解决方案2】:

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

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

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

    希望这能回答您的问题?

    【讨论】:

    • app_host 不会做任何事情,因为用户正在访问完整的 url(而不是路径),这将覆盖主机名,并且在配置块中设置当前驱动程序不会做任何事情在默认配置中,因为 current_driver 在每次测试开始时都会重置为 default_driver
    • 如何知道主机和端口是什么?我假设 Capybara 正在启动 rails 服务器。我应该调用什么方法来查询使用了哪个端口?
    • @Zack Capybara.current_session.server.port 应该是服务器启动后的端口,或者您可以通过设置 Capybara.server_port 来修复它,或者您可以设置 Capybara.always_include_port = true 让 Capybara 始终将端口插入 url没有提供特定端口的地方。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-08-26
    • 2021-02-14
    • 1970-01-01
    • 2021-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多