Automated browser testing with screenshots on Mac OSX using Ruby and Selenium

In this tutorial I'll show how to use the Selenium webdriver with Chrome and Ruby code to execute automated website tests and take screenshots along the way.

# create a new project space
$ mkdir selenium_testing

# create add a new gemset (optional)
$ echo "rvm use --create ruby-1.9.2@selenium_testing" > ./selenium_testing/.rvmrc

$ cd selenium_testing

# install selenium-webdriver gem
$ gem install selenium-webdriver

# ensure Google Chrome is installed in the correct location
$ file /Applications/Google\ Chrome.app/Contents/MacOS/Google\ Chrome 
/Applications/Google Chrome.app/Contents/MacOS/Google Chrome: Mach-O executable i386

# download chromedriver
# url: http://code.google.com/p/chromedriver/downloads/list
# @see: chromedriver_mac_20.0.1133.0.zip    ChromeDriver server for mac
# example:
$ curl -O http://chromedriver.googlecode.com/files/chromedriver_mac_20.0.1133.0.zip
$ unzip chromedriver_mac_20.0.1133.0.zip

# copy chromedriver into $PATH
$ sudo cp chromedriver /usr/bin/
$ which chromedriver
/usr/bin/chromedriver

Now you're ready to write some ruby code. I created a new file "test.rb":

#!/usr/bin/env ruby

# includes
require 'selenium-webdriver'

# create new chrome webdriver
driver = Selenium::WebDriver.for :chrome

# go to google
driver.navigate.to 'http://www.google.com'

# save screenshot
driver.save_screenshot('google.png')

# close webdriver
driver.close

Made the file executable, and executed it:

$ chmod +x test.rb
$ ./test.rb

A screenshot was created in the working directory.

google screenshot

Notice how the google screenshot was from an unauthenticated user? Here's another script that authenticates first, hits a list of urls, and takes a screenshot of each page:

#!/usr/bin/env ruby

# includes
require 'selenium-webdriver'
require 'uri'

# create new chrome webdriver
driver = Selenium::WebDriver.for :chrome

# go to login page
driver.navigate.to 'http://ericlondon.com/users/sign_in'

# enter user in username field
element = driver.find_element(:id, 'user_email')
element.clear
element.send_keys 'example@example.com'

# enter password
element = driver.find_element(:id, 'user_password')
element.clear
element.send_keys 'super_secret_password'

# click submit button
element = driver.find_element(:name, 'commit')
element.click

# define a list of URLs to test
urls = [
  'http://ericlondon.com',
  'http://ericlondon.com/recent-posts',
  'http://ericlondon.com/about',
]

# loop through URLs
urls.each do |url|

  # go to URL
  driver.navigate.to url

  # create filename
  uri = URI::parse(url)
  filename = "#{uri.host}_#{uri.path}".gsub!(/[^0-9A-Za-z]/, '_')
  driver.save_screenshot("#{filename}.png")

end

# close webdriver
driver.close