Ruby on Rails

Your Rails application might have an option to download a file, eg a CSV file with the products in your database.

When writing system tests to test our user interaction via the browser we want to basically click the download link, download the file and verify the file.

By default the file download will go to your default browser download folder, which you don’t have access to via your Rails application.

The trick is we can configure our application_system_test_case.rb file to set the path to a subfolder in the tmp folder like in the code below.

require "test_helper"
require "selenium/webdriver"
class ApplicationSystemTestCase < ActionDispatch::SystemTestCase

DOWNLOAD_PATH = Rails.root.join("tmp/downloads").to_s

Capybara.register_driver :chrome do |app|
profile = Selenium::WebDriver::Chrome::Profile.new
profile["download.default_directory"] = DOWNLOAD_PATH
Capybara::Selenium::Driver.new(app, :browser => :chrome, :profile => profile)
end

Capybara.default_driver = Capybara.javascript_driver = :chrome
driven_by :chrome, using: :chrome, screen_size: [1400, 1400]
end


Your system test can have a test like the one below:

test "can we export the file and are all fields in the header" do
visit partners_path
click_link "Export"
sleep 1
full_path = DOWNLOAD_PATH+"/partners-#{Date.today}.csv"
assert File.exist?(full_path)
headers = CSV.open(full_path, 'r') { |csv| csv.first.to_s }
assert_equal(headers,"[\"id\", \"name\", \"partner_type_id\", \"parent_id\", \"phone\", \"website\"]","Header does not match")
end

  1. Visit the path
  2. Click the Export link (make sure you have an id on your link
  3. sleep for 1 second to give it time to finish the download (for larger files you might need to increase the sleep
  4. You can asset the file exists in the path
  5. In case of a CSV file with headers you can open the file and read the first line with the headers
  6. Now you can assert the headers

Of course you can also assert each row or the count of rows.

Category
Tags

Comments are closed