Posted 3 months ago. Visible to the public.

Cucumber: Inspecting the Chrome download folder to test file downloads with Selenium

We already have some approaches on how to test file downloads withe selenium. Nonetheless here is another approach, which inspects the Chrome download folder. This way you do not need a separate logic on whether a file is served from a controller or a public path. The DownloadHelpers might also be re-used for reading e.g. a PDF file and checking its content.

Note: The step below will override a spreewald step and allows to use Regex for the filename. You might want to rename this step within you project in case you are using Spreewald.

features/step_definitions/spreewald_overrides_steps.rb

Copy
Then(/^I should get a download with filename "(.*?)"$/) do |filename| if Capybara.current_driver == :selenium patiently do expect(DownloadHelpers.last_download&.basename&.to_s).to match(filename) end else expect(response_headers['Content-Disposition']).to match(/filename=\"#{filename}\"/) end end

features/support/download_helpers.rb

Copy
# This is an adapted approach from # https://collectiveidea.com/blog/archives/2012/01/27/testing-file-downloads-with-capybara-and-chromedriver module DownloadHelpers TIMEOUT = 10 module_function def download_path download_path = Rails.root.join("tmp/test_downloads#{ENV['TEST_ENV_NUMBER']}") FileUtils.mkdir_p(download_path) download_path end def clear_downloads FileUtils.rm_r(download_path) if File.exist?(download_path) end def last_download downloads = Pathname.new(download_path) Timeout.timeout(TIMEOUT) do sleep 0.1 until downloads.glob('*.crdownload').blank? end downloads.children.sort_by(&File.method(:ctime)).last end end Before do DownloadHelpers.clear_downloads end After do DownloadHelpers.clear_downloads end

features/support/selenium.rb

Copy
Capybara.register_driver :selenium do |app| options = Selenium::WebDriver::Chrome::Options.new options.add_argument('--mute-audio') options.add_argument('--disable-infobars') options.add_preference('credentials_enable_service', false) options.add_preference('profile.password_manager_enabled', false) options.add_preference('download.default_directory', DownloadHelpers.download_path) Capybara::Selenium::Driver.new(app, browser: :chrome, options: options) end Before do Capybara.current_driver = :rack_test end Before('@javascript') do Capybara.current_driver = :selenium end

Once an application no longer requires constant development, it needs periodic maintenance for stable and secure operation. makandra offers monthly maintenance contracts that let you focus on your business while we make sure the lights stay on.

Owner of this card:

Avatar
Emanuel De
Last edit:
3 months ago
by Emanuel De
About this deck:
We are makandra and do test-driven, agile Ruby on Rails software development.
License for source code
Posted by Emanuel De to makandra dev
This website uses cookies to improve usability and analyze traffic.
Accept or learn more