How to use headless chrome with capybara and selenium

牧云@^-^@ 提交于 2019-12-05 03:31:05
Lucas Caton

1) Make sure you don't have another registered driver, I made this mistake myself and had an iphone driver, which was using the args in the old way, that's why I was getting the warning.

2) Make sure you have Chrome version 57+ on Linux, 59+ on macOS or 60+ on Windows;

3) Add/update the gem selenium-webdriver;

4) Add the following driver to your spec_helper.rb or rails_helper.rb:

Capybara.register_driver :chrome do |app|
  Capybara::Selenium::Driver.new app, browser: :chrome,
    options: Selenium::WebDriver::Chrome::Options.new(args: %w[headless disable-gpu])
end

Capybara.javascript_driver = :chrome

The simplest way to run headless Chrome with Rails apps is to add the following gems to the Gemfile

gem 'chromedriver-helper'
gem 'selenium-webdriver'

And update your application_system_test_case.rb with the following:

require "test_helper"

class ApplicationSystemTestCase < ActionDispatch::SystemTestCase
  driver = ENV['CHROME_HEADLESS'] == 'false' ? :selenium_chrome : :selenium_chrome_headless
  driven_by driver, screen_size: [1400, 1400]
end

There is no need to pass args as the drivers are already available to use, available drivers are :rack_test, :selenium, :selenium_chrome, :selenium_chrome_headless.

You can run Headless Chrome

$ bin/rails test:system

Or you can also run Chrome and see test running on it

$ CHROME_HEADLESS=false bin/rails test:system

Windows support is coming in Chrome 60.

Download "Chome Canary" and give the installation path as a binary in chromeOptions.

Download the latest "chromedriver" and add to path in Environment Variables.

require 'rubygems'
require 'capybara/cucumber'
require 'selenium-webdriver'

Capybara.register_driver :selenium_chrome do |app|
  caps = Selenium::WebDriver::Remote::Capabilities.chrome(
    "chromeOptions" => {
      "binary" => "C:/Users/YOURUSERNAME/AppData/Local/Google/Chrome SxS/Application/chrome.exe",
      "args" => [ "--disable-web-security", "--headless", "--disable-gpu" ]
    }
  )
  Capybara::Selenium::Driver.new(
    app, 
    browser: :chrome, 
    desired_capabilities: caps
  )
end

Capybara.default_driver = :selenium_chrome

I could get this working with the current version of Chrome, but it would display a blank window. If you want to get rid of that, then you need to use the "Chrome Canary" build.

The code below is a combination of the answers that @lucas-caton and @shawn-derik, but solves the issue I mentioned above.

Capybara.register_driver :chrome do |app|
  Capybara::Selenium::Driver.new(
    app,
    browser: :chrome,
    options: Selenium::WebDriver::Chrome::Options.new(
      binary: 'C:/Users/USERNAME/AppData/Local/Google/Chrome SxS/Application/chrome.exe',
      args: %w[no-sandbox headless disable-gpu]
    )
  )
end
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!