Download Online File

Context:

There are times when we might want to download files from online web sites or while we are testing a website to see if the link is not broken and that the file received is the right file when downloaded. Ruby has inbuilt Net::Http module for helping us download this. We are making a plain http call when downloading, so this is not a gem.

Relevant to Test Automation:

An example would be to download a pdf file and then verify that it contains certain text. In the previous section we have already seen how to parse a pdf file. This section we will see how to download any file

Agenda:

  • Important lines of code
  • Download yahoo messenger and save it and then delete it
  • cucumber scenario and step definitions
  • Output

1) link using href attribute:

Extract the href attribute of the web element and save it in a variable

2) URI, host and path:

Convert the source to URI and then extract the host and path variables

3) Start the download and save to file

Download using Net::HTTP and write the stream of bytes to a file “msgr11us.exe” in the current directory.¬†

4) Delete the file if it exists

File delete if file exists. If you do not wish to delete, then remove the below line of code and you can see the file downloaded and saved.

Cucumber Feature:

Step Definitions:

Ouput:

  • The file msgr11us.exe is downloaded to the current project root directory
  • Then the file is deleted later if it exists.
  • The output console should look as below

download_output

Closing Thoughts:

There are other ways to download a file without using the above method and that is automatically download the file when we initiate a download through websites. That is specified in Firefox profile section