水豚 chrome 无头确认对话框

capybara chrome headless confirm dialog

我正在尝试使用 chrome 和 capybara/selenium in rspec Ruby on Rails 的无头模式,尝试点击时出现错误在确认对话框中

Capybara.register_driver(:headless_chrome) do |app|
  capabilities = Selenium::WebDriver::Remote::Capabilities.chrome(
    chromeOptions: { args: %w[headless disable-gpu test-type window-size=1920x1080] }
  )

  driver = Capybara::Selenium::Driver.new(
    app,
    browser: :chrome,
    desired_capabilities: capabilities
  )

  driver
end

Capybara.server = :puma
Capybara.javascript_driver = :headless_chrome



scenario 'delete movie' do
  login_as user
  visit edit_public_movie_path(movie)

  expect(page).to have_selector('span[ng-click="ctrl.deleteMovie()"]')
  find('span[ng-click="ctrl.deleteMovie()"]').click

  page.driver.browser.switch_to.alert.accept

  wait_for_ajax(wait_after: 1)
  expect(page).to have_content('Click here to upload movie (Max: 500 MB)')
end

得到这个错误

 Event movie success delete movie
 Failure/Error: page.driver.browser.switch_to.alert.accept

 Selenium::WebDriver::Error::NoSuchAlertError:
   no alert open
     (Session info: headless chrome=59.0.3071.115)
     (Driver info: chromedriver=2.29.461585 (0be2cd95f834e9ee7c46bcc7cf405b483f5ae83b),platform=Mac OS X 10.12.5 x86_64)

在普通模式下,它可以正常工作。似乎硒不支持无头模式或需要其他方法来做到这一点。有任何想法吗?

更新(已解决)

所以,我花了很多时间寻找工作环境。

您需要最后构建 chromium,因为预览版有 bug. You can get it by these scripts linux or Mac

这是我的水豚配置

 Capybara.register_driver(:headless_chrome) do |app|
   capabilities = Selenium::WebDriver::Remote::Capabilities.chrome(
                                        chromeOptions: {
                                          args: %w[headless disable-gpu disable-popup-blocking no-sandbox window-size=1920x1920],
                                          binary: "#{Dir.home}/chromium-latest-#{platrofm}/latest/#{chrome_file}"
                                        })
  driver = Capybara::Selenium::Driver.new(app,
                                        browser: :chrome,
                                        desired_capabilities: capabilities)

  driver
end

Capybara.server = :puma
Capybara.javascript_driver = :headless_chrome
Capybara.default_max_wait_time = 20
Capybara.server_port = 55305

def platform
  if /linux/ =~ RUBY_PLATFORM
    "linux"
  else
    "macosx"
  end
end

def platform_linux?
  platform == "linux"
end

def chrome_file
  if platform_linux?
    "chrome"
  else
    "Chromium.app/Contents/MacOS/Chromium"
  end
end

你应该使用 page.driver.browser.switch_to.alert.accept 而不是 page.accept_alert

有同样的问题。请使用 chromeOptions 中的 disable-popup-blocking。