Automated Testing PDF in Selenium WebDriver
How to test downloading PDFs in Selenium WebDriver
--
Many websites feature links that download a PDF rather than just opening one. These PDF files’ content might be static (e.g. a restaurant menu or a booklet), or dynamically generated (e.g. a bank statement or a student’s grade report).
This tutorial will show you how to allow PDF downloads and verify the PDF contents in an automated test.
Test Design
- Navigate to a web page and download the PDF
For my example, I’m downloading a book sample PDF at http://zhimin.com/books/pwta. When you download it, you need to configure where the file is downloading to on your machine. - Verify the downloaded PDF exists
Once the file is downloaded from the browser, check if its downloaded successfully on your machine. - Read and verify the PDF’s contents
This step is not only for dynamically generated PDFs. It’s good practice to verify your PDF’s contents, even if it’s a static PDF.
Saving the download file to a specific location
First, let’s make sure we save the PDF to an area safe for testing. To test safely and avoid conflicts, download your PDF file to a test folder, and delete the PDF file after the test executes.
PDF verification library
Then use the ‘pdf-reader’ gem to verify the PDF. Install it on your command line with:
gem install pdf-reader
Open browser with specified download folder
To set a download location in Selenium WebDriver, you must update your browser options.
before(:all) do
# set up download settings
@download_path = "/Users/courtney/tmp"
options = Selenium::WebDriver::Chrome::Options.new
options.add_preference("download.prompt_for_download", false)
options.add_preference("download.default_directory", @download_path)
@driver = $driver = Selenium::WebDriver.for(:chrome, :options => options)
driver.get(site_url)
end
Setting prompt_for_download
to false means that you won’t receive a pop-up asking…