Skip to content

Instantly share code, notes, and snippets.

@natevick
Created January 9, 2020 22:56
Show Gist options
  • Save natevick/e5eb2478fd8b1da4838b7526385da282 to your computer and use it in GitHub Desktop.
Save natevick/e5eb2478fd8b1da4838b7526385da282 to your computer and use it in GitHub Desktop.
Capybara Initializers
class CapybaraInitializer
attr_accessor :headless, :context
alias :headless? :headless
def initialize
@headless = true
end
def call
# Common Capybara configuration
Capybara.default_max_wait_time = 5
# Add some Capybara config if we are running
# Chrome on the docker host machine.
if !headless? && docker?
Capybara.server_host = '0.0.0.0'
Capybara.server_port = '43447'
end
# Register the driver
Capybara.register_driver(:headless_chrome) { |app| driver(app) }
Capybara.javascript_driver = :headless_chrome
end
def self.configure
initializer = new
yield initializer if block_given?
initializer.call
end
private
def driver(app)
Capybara::Selenium::Driver.new(app, driver_options)
end
def driver_options
{ browser: :chrome, desired_capabilities: capabilities }.tap do |a|
a[:url] = 'http://host.docker.internal:9515/' if !headless? && docker?
end
end
def capabilities
Selenium::WebDriver::Remote::Capabilities.chrome(
'chromeOptions' => {
'args' => chrome_options
}
)
end
def chrome_options
%w(no-sandbox disable-gpu window-size=1440,900).tap do |a|
a << 'headless' if headless?
end
end
def docker?
context == :docker
end
end
# frozen_string_literal: true
RSpec.configure do |config|
headless = ENV.fetch('HEADLESS', true) != 'false'
config.before(:each, type: :system) do
driven_by :rack_test
end
config.before :each, type: :system, js: true do
# Docker environment
url = if headless
"http://#{ENV['SELENIUM_REMOTE_HOST']}:4444/wd/hub"
else
'http://host.docker.internal:9515'
end
driven_by :selenium, using: :chrome, options: {
browser: :remote,
url: url,
desired_capabilities: :chrome
}
Capybara.server = :puma, { Silent: true }
# Find Docker IP address
Capybara.server_host = if headless
`/sbin/ip route|awk '/scope/ { print $9 }'`.strip
else
'0.0.0.0'
end
Capybara.server_port = '43447'
Capybara.app_host = "http://#{Capybara.current_session.server.host}:#{Capybara.current_session.server.port}"
end
config.after :each, type: :system, js: true do
page.driver.browser.manage.logs.get(:browser).each do |log|
case log.message
when /This page includes a password or credit card input in a non-secure context/
# Ignore this warning in tests
next
else
message = "[#{log.level}] #{log.message}"
raise message
end
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment