Cristian M Cristian M - 13 days ago 6x
Ruby Question

Ruby / Watir-Webdriver - Cannot access the file after downloading it

I am working on a tests scenario that downloads a file from a website and adds it to folder.
For the download part, I am using the code described on the browser-downloads page within the Watir documentation.
The main problem was encountered in my tests when I am waiting for the file to be downloaded:

def verify_csv_file_exists
path = Dir.getwd + "/downloads/"
until File.exist?("#{path}*.csv") == true
sleep 1

When running the tests, the procedure above never stops, because it cannot see the file in the directory, although the file is downloaded.

Does anyone know a way how I can handle this situation?

Thank you.


You simply check the directory contents before you download the file, then wait until there's a new file added to the directory (by comparing the current content with the previous content). This is how you get the new file name:

This should do the job:

require 'watir-webdriver'

file_name = nil
download_directory = "#{Dir.pwd}/downloads"
download_directory.gsub!("/", "\\") if
downloads_before = Dir.entries download_directory

profile =
profile[''] = 2 # custom location
profile[''] = download_directory
profile['browser.helperApps.neverAsk.saveToDisk'] = "text/csv,application/pdf"

b = :firefox, :profile => profile

b.goto ''

30.times do
  difference = Dir.entries(download_directory) - downloads_before
  if difference.size == 1
    file_name = difference.first 
  sleep 1
raise "Could not locate a new file in the directory '#{download_directory}' within 30 seconds" if not file_name
puts file_name