Watir - Downloads



We have buttons or links in the UI or our website which downloads a pdf, or a doc. We can test that for using with Watir by giving some preferences to the browser.

The syntax for downloading −

prefs = {
   'download' => {
      'default_directory' => "C:/download",
      'prompt_for_download' => false,
   }
}
b = Watir::Browser.new :chrome, options: {prefs: prefs}

The prefs has download wherein we need to give the path where we want the file to be stored after download and the same has to be given to the browsers using options as shown in the syntax above.

A working example is shown here. Here, we have created test page with a button, which when clicked will download a file called file.txt as shown below −

<html>
   <head>
      <title>Testing UI using Watir</title>
   </head>
   
   <body>
      <br/>
      <br/>
      <button id = "btnsubmit">
         <a href = "file.txt" download>Click to Download!</a>
      </button>
      <br/>
   </body>
</html>

file.txt

This is for testing watir download

Output

Testing Watir

When you click the download button, the file is downloaded.

Now let us test the same using Watir −

require 'watir'
prefs = {
   'download' => {
      'default_directory' => "C:/download",
      'prompt_for_download' => false,
   }
}
b = Watir::Browser.new :chrome, options: {prefs: prefs}
b.goto('http://localhost/uitesting/filedownload.html')
b.button(id: 'btnsubmit').click
b.screenshot.save 'testdownload.png'

The path we have given to store the downloaded file is "C:/download". When we execute above code we will have the file download in download path given as shown below −

download path

The output testdownload.png is as shown here −

testdownload

Advertisements