The Issue

Uploading a file during an automated test may seem like it would require an advanced function; it is as simple as any other basic Selenium or Watir-Webdriver command. Instead of clicking an Upload button, and clicking through the popup window to find our file, we can input the path directly into our browser via the file field HTML.

The Answer

We will utilize the following Watir Webdriver command:

The browser.file_field.set command will let us define our local filepath, which will upload the file into our browser. Our filepath is placed after the .set in quotations, per the above example. Lets implement this into an automated test script.

The Code

We will navigate to an image hosting site, and upload our file. After uploading, we will validate and display that the file was successfully uploaded:

The Result

We will upload our file directly and bypass clicking "Choose Images".

We will upload our file directly and bypass clicking “Choose Images”.

After we save and run the automation file (ImageUpload.rb), we can view the results:

  • Browser Opens
  • Navigates to Postimage.org
  • File is uploaded through our command
  • We validate that the file has been uploaded

We can see here the command line result displaying our validation:

Capture123123

 

 

The Takeaway

Uploading a file into your browser during an automated test may have been previously been a blocker, or an issue requiring an advanced function to solve. Even just one well-placed Selenium or Watir-Webdriver command can save an exponential amount of time in your automated browser test runs.