Cristian M
Cristian M

Reputation: 357

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
     end 
    end

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.

Upvotes: 2

Views: 2528

Answers (3)

Alister Scott
Alister Scott

Reputation: 3685

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 Selenium::WebDriver::Platform.windows?
downloads_before = Dir.entries download_directory

profile = Selenium::WebDriver::Firefox::Profile.new
profile['browser.download.folderList'] = 2 # custom location
profile['browser.download.dir'] = download_directory
profile['browser.helperApps.neverAsk.saveToDisk'] = "text/csv,application/pdf"

b = Watir::Browser.new :firefox, :profile => profile

b.goto 'https://dl.dropbox.com/u/18859962/hello.csv'

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

Upvotes: 5

pguardiario
pguardiario

Reputation: 54984

Try it like this instead:

Dir.glob('downloads/*.csv').any?

Also how is sleeping for 1 second supposed to change anything? Is this a multithreaded app?

Upvotes: 0

nonowarn
nonowarn

Reputation: 640

You can't use "glob" with File.exists? like File.exists?("*.csv"). It checks whether the file named *.csv exists, not any file with name ends with .csv. You should use exact file name to check if a file exists.

Upvotes: 0

Related Questions