Class: SeleniumChromeHelper::Railtie

Inherits:
Rails::Railtie
  • Object
show all
Defined in:
lib/selenium_chrome_helper/railtie.rb

Overview

This Railtie configures Capybara to use a specific version of Google Chrome for testing. It registers two drivers: one for headless testing and one for non-headless testing.

Class Method Summary collapse

Class Method Details

.base_pathObject



22
23
24
25
# File 'lib/selenium_chrome_helper/railtie.rb', line 22

def self.base_path
  custom = ENV['CHROME_FOR_TESTING_PATH']
  Pathname.new(custom || Rails.root.join('.chrome-for-testing', CHROME_VERSION))
end

.chrome_pathObject



38
39
40
41
42
43
44
45
46
47
48
# File 'lib/selenium_chrome_helper/railtie.rb', line 38

def self.chrome_path
  path = if platform.start_with?('mac')
           base_path.join("chrome-#{platform}", 'Google Chrome for Testing.app', 'Contents',
                          'MacOS', 'Google Chrome for Testing')
         else
           base_path.join("chrome-#{platform}", 'chrome')
         end
  warn "⚠️ Chrome binary not found at #{path}. Did you run `rake chrome:install`?" unless File.exist?(path)

  path.to_s
end

.configure_browser_options(headless: true) ⇒ Object



57
58
59
60
61
62
63
64
65
# File 'lib/selenium_chrome_helper/railtie.rb', line 57

def self.configure_browser_options(headless: true)
  options = Selenium::WebDriver::Chrome::Options.new
  options.binary = chrome_path
  options.add_argument('--headless=new') if headless
  options.add_argument('--disable-gpu')
  options.add_argument('--no-sandbox')
  options.add_argument('--window-size=1400,1400')
  options
end

.driver_pathObject



50
51
52
53
54
55
# File 'lib/selenium_chrome_helper/railtie.rb', line 50

def self.driver_path
  path = base_path.join("chromedriver-#{platform}", 'chromedriver')
  warn "⚠️ Chromedriver not found at #{path}. Did you run `rake chrome:install`?" unless File.exist?(path)

  path.to_s
end

.platformObject



27
28
29
30
31
32
33
34
35
36
# File 'lib/selenium_chrome_helper/railtie.rb', line 27

def self.platform
  case RUBY_PLATFORM
  when /darwin/
    `uname -m`.strip == 'arm64' ? 'mac-arm64' : 'mac-x64'
  when /linux/
    'linux64'
  else
    raise "Unsupported platform: #{RUBY_PLATFORM}"
  end
end

.register_driver(name, headless:) ⇒ Object



67
68
69
70
71
72
73
# File 'lib/selenium_chrome_helper/railtie.rb', line 67

def self.register_driver(name, headless:)
  Capybara.register_driver name do |app|
    Selenium::WebDriver::Chrome::Service.driver_path = driver_path
    options = configure_browser_options(headless: headless)
    Capybara::Selenium::Driver.new(app, browser: :chrome, options: options)
  end
end