chrome驱动程序在第一次测试后关闭 chrome

chromedriver closing chrome after first test

我在 Rails 3.2 上使用带有 google-chrome-beta 60.0.3112.50-1 的 Chromedriver 2.30.477691 和 Selenium-webdriver 3.4.3,我的问题是只有第一个集成测试通过,然后浏览器关闭,所有其他集成测试失败,无论它们是在同一个 rspec 文件还是单独的文件中。

如果我 运行 任何一个有重点的测试,它就会通过。我已经尝试过使用和不使用无头选项,这没有什么区别,在第一次测试后我可以看到浏览器已关闭并且不会为以后的测试重新打开。

这些测试是 运行 使用 firefox 进行的,所以我知道这些测试 运行 很好。

这是我在 rails_helper.rb

中的设置
  Capybara.register_driver(:headless_chrome) do |app|
    caps = Selenium::WebDriver::Remote::Capabilities.chrome(
      chromeOptions: {
        binary: "/opt/google/chrome-beta/google-chrome",
        args: %w[headless disable-gpu]
      }
    )
    Capybara::Selenium::Driver.new(
      app,
      browser: :chrome,
      desired_capabilities: caps
    )
  end

  Capybara.current_driver =:headless_chrome
  Capybara.javascript_driver = :headless_chrome

我的一个测试示例,如果它不是序列中的第一个测试就会失败。

require "rails_helper"

RSpec.describe "Account Index Page Tests", :type => :feature do

    before :each do
      admin_sign_in
    end

    it "Ensure that the index contains one of the default accounts" do
      visit "/#/accounts"

      expect(find_by_id("heading")).to have_text("Account")
      expect(find_by_id("new-btn")).to have_text("New")
      expect(find_by_id("name0")).to have_text("Sales")
    end
end

在 运行将上述测试作为第二次测试后,我得到了这个错误。如果我 运行 这个顺序相反,那么另一个测试将失败而不是 index_accounts.

% rspec spec/integration/accounts/create_accounts_spec.rb spec/integration/accounts/index_accounts_spec.rb

Randomized with seed 30251
.F

Failures:

  1) Account Index Page Tests Ensure that the index contains one of the default accounts
     Failure/Error: fill_in "Email", with: "admin@example.com.au"

     Capybara::ElementNotFound:
       Unable to find field "Email"
     # ./spec/integration_helpers/login_helper.rb:43:in `admin_sign_in'
     # ./spec/integration/accounts/index_accounts_spec.rb:7:in `block (2 levels) in <top (required)>'

Finished in 5.57 seconds (files took 6.2 seconds to load)
2 examples, 1 failure

Failed examples:

rspec ./spec/integration/accounts/index_accounts_spec.rb:10 # Account Index Page Tests Ensure that the index contains one of the default accounts

假设您使用默认的 rspec 配置 Capybara,它会安装一个 before 块,根据测试元数据设置要使用的驱动程序,以及一个 after 块,将驱动程序重置为 Capybara.default_driver - https://github.com/teamcapybara/capybara/blob/master/lib/capybara/rspec.rb#L20

您遇到的问题是您设置了 Capybara.current_driver 而不是 Capybara.default_driver。这意味着您的第二个和进一步的测试将被重置为使用默认的 rack_test 驱动程序(因为您没有用于在测试中分配不同驱动程序的元数据)。如果您只是希望所有测试都默认使用 :headless_chrome 驱动程序而不用担心元数据更改

Capybara.current_driver = :headless_chrome
Capybara.javascript_driver = :headless_chrome

Capybara.default_driver = :headless_chrome
Capybara.javascript_driver = :headless_chrome

current_driver 的设置将由前面提到的前后块处理。