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:
1 |
browser.file_field.set "C:\\Sample\\File\\Path.PNG" |
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:
1 2 3 4 5 6 7 |
#ImageUpload.rb require 'watir-webdriver' require 'rubygems' browser = Watir::Browser.new :chrome browser.goto "https://postimage.org/" browser.file_field.set "C:\\Users\\Admin\\Desktop\\Capture.PNG" puts "File is uploaded: #{browser.element(:text,"Capture.PNG").exists?}" |
The Result
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:
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.