Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Rails Capybara chromedriver setup for testing downloads
# in rails_helper.rb
driver = if ENV['CHROME_DEBUG'] == 'true'
Capybara.register_driver :chrome do |app|
Capybara::Selenium::Driver.new(app, browser: :chrome)
end
:chrome
else
Capybara.register_driver :headless_chrome do |app|
browser_options = ::Selenium::WebDriver::Chrome::Options.new
browser_options.add_argument('headless')
browser_options.add_argument('disable-gpu')
browser_options.add_argument('window-size=1400,1200')
browser_options.add_preference('download.default_directory', Rails.root.join('tmp/downloads'))
Capybara::Selenium::Driver.new(app, browser: :chrome, options: browser_options)
end
:headless_chrome
end
Capybara.javascript_driver = driver
Capybara.default_driver = driver
Capybara.server = :puma, { Silent: true }
Capybara.raise_server_errors = true
Capybara.server_errors << Exception
# spec/support/helpers/download_helper.rb
module DownloadHelpers
TIMEOUT = 10
PATH = Rails.root.join('tmp/downloads')
def downloads
Dir[PATH.join('*')]
end
def last_download
downloads.last
end
def last_download_contents
wait_for_download
File.read(last_download)
end
def clear_downloads
FileUtils.rm_f(downloads)
end
private
def wait_for_download
Timeout.timeout(TIMEOUT) do
sleep 0.1 until downloaded?
end
end
def downloaded?
!downloading? && downloads.any?
end
def downloading?
downloads.grep(/\.crdownload$/).any?
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.