Testing for downloading file in a feature test

166 Views Asked by At

Currently, my code downloads data in the Controller using send_data. I need to write a feature test to check for the download of the file. I'm using Capybara, selenium (chrome browser). Is there a way to 1. check to see if the file has been downloaded and 2. stop the file from being created in the local download folder e.g. is there a way to intercept the download and store it in a test folder to be able to check it? Or maybe to catch the data rather than the file actually being built? Thank you for your help.

My code to create the file is simply:

send_data csv_data, type: 'text/csv; charset=utf-8; header=present', disposition: "attachment; filename=<filename>"
2

There are 2 best solutions below

0
Hywel Griffiths On BEST ANSWER

Ok so the answer was a small workaround that did the correct testing. :headless_chrome will put the downloaded file amongst the app, rather than into the user downloads. I found out that you can attach two drivers, both :chrome and :headless_chrome and switched between the two when I wanted to test if files were downloaded.

3
sashkins On

The general approach I'm using for the 'download' process testing in UI is the following:

  1. Setup the default download directory for your driver to the required folder (some test folder in your case (example)
  2. Capture the number of files in your test folder before the download (example)
  3. Do the required actions on the page to start the download process
  4. Wait for the number of files in the test directory to be +1 (simple loop with some timeout)
  5. Get the last modified file from the test directory (example)
  6. Wait for the required file extension, just to be sure that the file is fully downloaded (again, simple loop with some timeout, repeating step 5).
  7. Validate filename/contents/etc depending on your needs.