Header logo Open Menu Close Menu
  • Live
  • Automate
  • App Live
  • App Automate
  • More
    • Enterprise
    • Screenshots
    • Responsive
  • Pricing
  • Resources Resources
      • Languages
      • Java
      • NodeJS
      • C#
      • Python
      • PHP
      • Ruby
      • Perl
      • Frameworks
        • Behat
        • Behave
        • Capybara
        • Codeception
        • Cucumber
        • Gauge
        • Intern
        • JBehave
        • JUnit
        • Lettuce
        • MbUnit
        • Nightwatch
        • NUnit
        • PHPUnit
        • PNUnit
        • Protractor
        • RSpec
        • Selenide
        • Serenity
        • Specflow
        • TestNG
        • WD
        • Webdriverio
      • Documentation
        • Continuous Integration
        • Jenkins Plugin
        • Travis CI add-on
        • TeamCity
        • Bamboo CI
        • Browsers & Devices
        • Physical Mobile Devices
        • Capabilities
        • Rest API
        • Status Badges
        • JS Testing
        • Timeouts
        • Local Testing
        • Debugging Tools
        • Parallel Testing
    • BrowserStack for Open Source
      Learn More
      • Features
      • Live Features
      • Browsers & Platforms
      • Developer Tools
      • Local Testing
      • Security
      • Mobile
      • Test on Right Devices
      • Mobile Features
    • BrowserStack for Open Source
      Learn More
  • Sign in
  • Free Trial
  • Resources
  • Features
  • Mobile
  • Features
  • Live Features
  • Browsers & Platforms
  • Developer Tools
  • Local Testing
  • Security
  • Enterprise Features
  • Open Source
  • Mobile
  • Test on Right Devices
  • Mobile Features

Support Automate Ruby

Selenium with Ruby

Your guide to running Selenium Webdriver tests with Ruby on BrowserStack.

Introduction

BrowserStack gives you instant access to our Selenium Grid of 1100+ real devices and desktop browsers. Running your Selenium tests with Ruby on BrowserStack is simple. This guide will help you:

  1. Run a sample Selenium Webdriver test on BrowserStack
  2. Setup your environment to be able to test URLs in your internal network
  3. Understand and configure the core capabilities in your Selenium test suite
  4. Explore advanced features

Prerequisites

Before you can start Selenium testing in Ruby, you have to first install the Selenium bindings for Ruby. Use this Ruby gem to install the selenium-webdriver bindings from your command line:

#Install using rubygems
gem install selenium-webdriver

Getting Started

Note: Running your Selenium tests on BrowserStack requires a username and an access key.

To obtain your username and access keys, sign up for a Free Trial or purchase a plan.

To get started, let’s run a simple Selenium Webdriver test. The Ruby script below will open a URL, input a string, submit the form, and return the page title.

First, select the OS and Device/Browser combination you'd like to test on the using drop-down menus below. This will automatically update the Ruby code sample below:

1. Select an OS
iOS
Mobile
  • iOS
  • Android
Desktop
  • Windows 10
  • Windows 8.1
  • Windows 8
  • Windows 7
  • Windows XP
  • OS X High Sierra
  • OS X Sierra
  • OS X El Capitan
  • OS X Yosemite
  • OS X Mavericks
  • OS X Mountain Lion
  • OS X Lion
  • OS X Snow Leopard
2. Select a browser
Windows XP
2. Select a device
iOS
3. Select a resolution
1024 x 768
Resolution

    Look for the icon to select a real device.

    Note: Testing on real devices requires the Automate Mobile plan

    require 'rubygems'
    require 'selenium-webdriver'
    
    # Input capabilities
    caps = Selenium::WebDriver::Remote::Capabilities.new
    
    caps["browser"] = "IE"
    caps["browser_version"] = "7.0"
    caps["os"] = "Windows"
    caps["os_version"] = "XP"
    caps["browserstack.debug"] = "true"
    caps["name"] = "Testing Selenium 2 with Ruby on BrowserStack"
    
    
    driver = Selenium::WebDriver.for(:remote,
      :url => "http://USERNAME:ACCESS_KEY@hub-cloud.browserstack.com/wd/hub",
      :desired_capabilities => caps)
    driver.navigate.to "http://www.google.com"
    element = driver.find_element(:name, 'q')
    element.send_keys "BrowserStack"
    element.submit
    puts driver.title
    driver.quit
    

    Warning: The driver.quit statement is required, otherwise the test continues to execute, leading to a timeout.

    Second, copy-and-paste the code sample into your code editor, save it as a .rb file, and execute the test from your command line.

    Third, verify the results. The Selenium Webdriver test should have opened a URL, inputted a string, submitted the form, and returned the page title. Your results will be displayed on the command-line interface and on the Automate dashboard, where you can see Text Logs, Screenshots of every Selenium command, and a Video Recording of your entire test.

    Testing on Internal Networks

    BrowserStack enables you to run automated tests on your internal development environments, on localhost, and from behind a corporate firewall. This feature is called "Local Testing".

    Local Testing establishes a secure connection between your machine and the BrowserStack cloud. Once you set up Local Testing, all URLs work out of the box, including HTTPS URLs and those behind a proxy or firewall.

    Getting Started

    In two steps, configure your Selenium Webdriver tests for Local Testing:

    1. Download and run the BrowserStackLocal binary:

      Download the appropriate binary:

      • OS X 
      • Linux 32-bit 
      • Linux 64-bit 
      • Windows 

      The download links are secure. The binaries are digitally signed, identifying the publisher as BrowserStack Ltd. Read more about our security.

      Navigate to the folder containing the binary, and run it from the command line.

      • OS X & Linux
      • Windows
      ./BrowserStackLocal --key ACCESS_KEY
      
    2. Once the connection is established, enable local testing in your tests by setting the browserstack.local capability to true.
    3. caps['browserstack.local'] = 'true'
      

    Multiple Local Testing connections

    You will often want to run multiple Selenium Webdriver tests in parallel through the same BrowserStack account. If these parallel tests are using the Local binary, you can setup unique named connections using the local-identifier command line option:

    1. Run the BrowserStackLocal binary with the localIdentifier option

      • OS X & Linux
      • Windows
      ./BrowserStackLocal --key ACCESS_KEY --local-identifier Test123
      Here, we have created a named connection called Test123.
    2. Once the connection is made, you need to set the browserstack.localIdentifier in your test with the correct named connection:

      caps['browserstack.local'] = 'true'
      caps['browserstack.localIdentifier'] = 'Test123'
      

    Note: Learn more about other common local testing use cases such as testing behind a firewall, proxy, browsermob proxy and whitelisting IPs.

    Configuring capabilities

    To run your Ruby-based test suite on our Selenium grid, you have to configure a couple of capabilities so that your tests execute on a remote browser.

    If the test was running on the Firefox browser on your machine, you would have the following code:

    driver = Selenium::WebDriver.for :firefox
    

    To run on BrowserStack, the Selenium Webdriver capabilities have to be changed. In this example, the test is configured to run on a remote Firefox browser:

    driver = Selenium::WebDriver.for(:remote,
      :url => "http://USERNAME:ACCESS_KEY@hub-cloud.browserstack.com/wd/hub",
      :desired_capabilities => Selenium::WebDriver::Remote::Capabilities.firefox)
    

    For a full reference of all the Selenium and custom capabilities we support, visit our Capabilities page.

    Run tests on desktop browsers and real mobile devices

    To run your Selenium test on a particular OS and Device/Browser combination, select from the drop-down menus below. The capabilities you need to pass in your Selenium test suite will then be generated.

    1. Select an OS
    iOS
    Mobile
    • iOS
    • Android
    Desktop
    • Windows 10
    • Windows 8.1
    • Windows 8
    • Windows 7
    • Windows XP
    • OS X High Sierra
    • OS X Sierra
    • OS X El Capitan
    • OS X Yosemite
    • OS X Mavericks
    • OS X Mountain Lion
    • OS X Lion
    • OS X Snow Leopard
    2. Select a browser
    Windows XP
    2. Select a device
    iOS
    3. Select a resolution
    1024 x 768
    Resolution

      icon indicates a real mobile device

      Note: Testing on real devices requires the Automate Mobile plan

      caps[:browserName] = 'iPhone'
      caps[:platform] = 'MAC'
      caps['device'] = 'iPhone 5'
      

      For a list of all supported devices, visit the Browsers and Platforms page.

      Builds and projects

      Keep track of all your automated tests using the build and project capabilities. Group your tests into builds, and builds further into projects.

      caps['build'] = 'version1'
      caps['project'] = 'newintropage'
      

      Note: Allowed characters include uppercase and lowercase letters, digits, spaces, colons, periods, and underscores. Other characters, like hyphens or slashes are not allowed.

      Self-signed certificates

      To avoid invalid certificate errors while testing on BrowserStack Automate, set the acceptSslCerts capability in your test to true.

      caps['acceptSslCerts'] = 'true'
      

      Enable and Disable Flash

      Chrome

      To disable Flash in Chrome, create a chromeOptions capability, and pass the --disable-plugins argument to the capability.

      caps = Selenium::WebDriver::Remote::Capabilities.chrome
      caps["chromeOptions"] = {}
      caps["chromeOptions"]["args"] = ["--disable-plugins"]
      

      Warning: the --disable-plugins modifier turns off all the plugins in the browser.

      Firefox

      It is possible to disable Flash within Firefox, by setting the profile capability to 0. Flash is enabled by default.

      profile = Selenium::WebDriver::Firefox::Profile.new
      profile["plugin.state.flash"] = 0
      caps = Selenium::WebDriver::Remote::Capabilities.firefox(:firefox_profile => profile)
      
      Internet Explorer

      To disable Flash in Internet explorer, pass the browserstack.ie.noFlash capability in your tests.

      caps["browserstack.ie.noFlash"] = "true"
      

      Enable and Disable Pop-ups

      Chrome

      Popup blocker is disabled by default in Chrome >= 43. To enable the popup blocker, create a chromeOptions capability, and pass the disable-popup-blocking as excludeSwitches to the capability.

      caps = Selenium::WebDriver::Remote::Capabilities.chrome
      caps["chromeOptions"] = {}
      caps["chromeOptions"]["excludeSwitches"] = ["disable-popup-blocking"]
      

      To disable the popup blocker in Chrome < 43, create a chromeOptions capability, and pass the --disable-popup-blocking argument to the capability.

      caps = Selenium::WebDriver::Remote::Capabilities.chrome
      caps["chromeOptions"] = {}
      caps["chromeOptions"]["args"] = ["--disable-popup-blocking"]
      
      IE

      To enable the popups in IE, use the browserstack.ie.enablePopups capability.

      caps['browserstack.ie.enablePopups'] = 'true'
      
      Safari

      To enable the popups in Safari, use the browserstack.safari.enablePopups capability.

      caps['browserstack.safari.enablePopups'] = 'true'
      

      Debugging

      BrowserStack provides a range of debugging tools to help you quickly identify and fix bugs you discover through your automated tests.

      Text Logs

      Text Logs are a comprehensive record of your test. They are used to identify all the steps executed in the test and troubleshoot errors for the failed step. Text Logs are accessible from the Automate dashboard or via our REST API.

      Visual Logs

      Visual Logs automatically capture the screenshots generated at every Selenium command run through your Ruby script. Visual logs help with debugging the exact step and the page where failure occurred. They also help identify any layout or design related issues with your web pages on different browsers.

      Visual Logs are disabled by default. In order to enable Visual Logs you will need to set browserstack.debug capability to 'true':

      caps['browserstack.debug'] = 'true'
      
      Video Recording

      Every test run on the BrowserStack Selenium grid is recorded exactly as it is executed on our remote machine. This feature is particularly helpful whenever a browser test fails. You can access videos from Automate Dashboard for each session. You can also download the videos from the Dashboard or retrieve a link to download the video using our REST API.

      Note: Video recording increases test execution time slightly. You can disable this feature by setting the browserstack.video capability to false.

      caps['browserstack.video'] = 'false'
      
      Console Logs

      Console Logs capture the browser's console output at various steps of the test to troubleshoot javascript issues. You can retrieve Console Logs using our REST API. You will also be able to download logs from Automate Dashboard.

      Console Logs are enabled with log level set to 'errors' by default. To set different log levels, you need to use the capability browserstack.console with values 'disable', 'errors', 'warnings', 'info' or 'verbose', as shown below:

      caps['browserstack.console'] = 'warnings'
      
      Network Logs

      Network Logs capture the browser's performance data such as network traffic, latency, HTTP requests and responses in the HAR format. You can download network logs using the REST API or from the Automate Dashboard. You can visualize HAR files using the HAR Viewer.

      Network Logs are disabled by default. To enable Network Logs use the capability browserstack.networkLogs with the value 'true', as shown below:

      caps['browserstack.networkLogs'] = 'true'
      

      ChromeOptions

      A ChromeDriver session can further be customized and configured using ChromeOptions. BrowserStack supports the full complement of ChromeOptions. In this example, ChromeOptions is used to disable flash in Chrome.

      caps = Selenium::WebDriver::Remote::Capabilities.chrome
      caps["chromeOptions"] = {}
      caps["chromeOptions"]["args"] = ["--disable-plugins"]
      

      Firefox Profile

      To change the preferences within Firefox, instantiate a new Firefox Profile object and update the preferences of the profile. Check out more preferences at the MozillaZine Knowledge Base.

      In this example, a custom Firefox Profile is used to disable flash in Firefox.

      profile = Selenium::WebDriver::Firefox::Profile.new
      profile["plugin.state.flash"] = 0
      caps = Selenium::WebDriver::Remote::Capabilities.firefox(:firefox_profile => profile)
      

      Speed up testing

      The BrowserStack Selenium grid gives you the infrastructure you need to scale. Features like Parallel Testing and Queueing enable you to scale faster.

      Parallel Testing

      On BrowserStack, you can run multiple Selenium Webdriver tests at the same time across various browser, device and OS combinations. This is “Parallel Testing”. Parallel Testing gives you the same benefits as running a multi-threaded application.

      With Parallel Testing, you can run the same test on different browser/device combinations, or run different tests on the same browser/device combination. Parallel Testing will help you reduce the run time of your test suite, resulting in faster build times and faster releases.

      To start Parallel testing, you can use any of the popular test frameworks which work with Ruby and Selenium. We have provided examples further down in this article.

      Note: Achieve your test coverage and build execution time goals by using our calculator to understand how many parallel sessions you need.

      Queuing

      With queuing, you can launch an additional number of parallel tests with different browser configurations that will be queued in a sequence. For instance, if you want to run 5 additional tests, apart from your subscribed limit of 2 parallel tests, BrowserStack will queue the additional 5 tests until one of the 2 initial tests finish, and a slot is available for execution. With queuing, you don't need to worry about managing your test pipeline - we automatically take care of scheduling and execution for you.

      With this feature, accounts up to 5 parallel tests can queue 5 tests. Beyond 5 parallel tests, an equivalent number of tests will be queued.

      Note: The wait limit for the execution of a pending queued job is 15 minutes and will be cancelled if exceeded.

      We have provided examples of parallel testing implementation using popular testing frameworks. In order to increase the number of tests, purchase more parallel tests of your Automate or Automate Pro plan to get access to more tests.

      Add-on

      We provide a ‘fast-selenium’ add-on to speed up your tests even more. All you have to do is download it, and include it in your code, with a require statement:

      Show code snippet

      require './fast-selenium'
      

      Note: To run this patch, the Curb gem has to be included in the project Gemfile.

      Advanced features

      BrowserStack offers you the ability to harness the advanced capabilities of Selenium to ensure you can test every scenario with your test suite.

      Taking screenshots

      To take screenshots automatically from within the tests:

      Show code snippet

      driver.save_screenshot("screenshots.png")
      

      Basic HTTP Authentication

      If the website uses basic authentication, use the code snippet below as a reference to connect to the website via your Selenium tests

      driver.navigate.to("http://<username>:<password>@yourdomain")
      

      Uploads & Downloads

      Upload

      To upload files through tests:

      driver.file_detector = lambda do |args|
        str = args.first.to_s
        str if File.exist?(str)
      end
      driver.navigate.to "http://www.fileconvoy.com"
      driver.find_element(:id, "upfile_0").send_keys("C:\\Users\\hello\\url.txt");
      driver.find_element(:id, "readTermsOfUse").click;
      driver.find_element(:name, "form_upload").submit;
      sleep(5)
      
      Download

      To download files through the test files, you need to create a profile capability containing all the necessary parameters, and then associate it with the WebDriver.

      profile = Selenium::WebDriver::Firefox::Profile.new
      profile['browser.download.folderList'] = 0
      profile['browser.download.manager.showWhenStarting'] = false
      profile['browser.download.manager.focusWhenStarting'] = false
      profile['browser.download.useDownloadDir'] = true
      profile['browser.helperApps.alwaysAsk.force'] = false
      profile['browser.download.manager.alertOnEXEOpen'] = false
      profile['browser.download.manager.closeWhenDone'] = true
      profile['browser.download.manager.showAlertOnComplete'] = false
      profile['browser.download.manager.useWindow'] = false
      # you will need to find the content-type of your app and set it here.
      profile['browser.helperApps.neverAsk.saveToDisk'] = "application/octet-stream"
      caps = Selenium::WebDriver::Remote::Capabilities.firefox(:firefox_profile => profile)
      driver = Selenium::WebDriver.for(:remote,
                                       :url => "http://USERNAME:ACCESS_KEY@hub-cloud.browserstack.com/wd/hub",
                                       :desired_capabilities => caps)
      driver.navigate.to "https://rubygems.org/gems/selenium-webdriver"
      driver.find_element(:id => 'download').click
      driver.quit
      

      Session ID

      To obtain the session ID of a running BrowserStack Automate session:

      @driver.session_id
      

      Running tests from behind a proxy

      To run your tests from behind your local proxy:

      @driver.proxy = Selenium::Proxy.new(:http => "proxy.org:8080")
      

      REST API

      It is possible to mark tests as either a pass or a fail, using the following snippet:

      require 'rest-client'
      RestClient.put "https://USERNAME:ACCESS_KEY@api.browserstack.com/automate/sessions/<session-id>.json", {"status"=>"passed", "reason"=>""}, {:content_type => :json}
      

      The two potential values for status can either be passed or failed. Optionally, a reason can also be passed.

      Using test frameworks

      Ruby has several popular testing frameworks, and we have provided examples on how to use them in conjunction with Automate. To download the examples displayed here, visit BrowserStack's repository on Github.

      Test::Unit

      Single test

      In the following test, the username and access key are inputted via the test.

      require 'rubygems'
      require 'selenium-webdriver'
      require 'test/unit'
      
      class SampleTest < Test::Unit::TestCase
        def setup
          url = "http://USERNAME:ACCESS_KEY@hub-cloud.browserstack.com/wd/hub"
          @driver = Selenium::WebDriver.for(:remote, :url => url)
        end
      
        def test_post
          @driver.navigate.to "http://www.google.com"
          element = @driver.find_element(:name, 'q')
          element.send_keys "BrowserStack"
          element.submit
          assert_equal(@driver.title, "BrowserStack - Google Search")
        end
      
        def teardown
          @driver.quit
        end
      end
      
      Parallel tests

      Add the parallel testing gem to the project Gemfile, group all your tests together, and run the command. Each of the tests has to be configured to run remotely, as described above.

      The example below uses the Test::Unit framework to run parallel tests, using two tests. The username and access key are set as environment variables within the code, which when passed as parameters to the program, they are then accessible throughout the testing framework.

      Test 1: google-search-browserstack-chrome-mac.rb

      require 'rubygems'
      require 'selenium-webdriver'
      require 'test/unit'
       
      class SampleTest1 < Test::Unit::TestCase
        def setup
          username=ENV['BS_USERNAME']
          key=ENV['BS_AUTHKEY']
          url = "http://#{username}:#{key}@hub-cloud.browserstack.com/wd/hub"
          capabilities = Selenium::WebDriver::Remote::Capabilities.chrome
          capabilities.platform = :MAC
          @driver = Selenium::WebDriver.for(:remote, :url => url,  :desired_capabilities => capabilities)
        end
       
        def test_post
          @driver.navigate.to "http://www.google.com"
          element = @driver.find_element(:name, 'q')
          element.send_keys "BrowserStack"
          element.submit
          assert_equal(@driver.title, "BrowserStack - Google Search")
        end
       
        def teardown
          @driver.quit
        end
      end
      

      Test 2: google-search-browserstack-ie9.rb

      require 'rubygems'
      require 'selenium-webdriver'
      require 'test/unit'
       
      class SampleTest2 < Test::Unit::TestCase
        def setup
          username=ENV['BS_USERNAME']
          key=ENV['BS_AUTHKEY']
          url = "http://#{username}:#{key}@hub-cloud.browserstack.com/wd/hub"
          capabilities = Selenium::WebDriver::Remote::Capabilities.internet_explorer
          capabilities.version = "9.0"
          capabilities.platform = :WINDOWS
          @driver = Selenium::WebDriver.for(:remote, :url => url,  :desired_capabilities => capabilities)
        end
       
        def test_post
          @driver.navigate.to "http://www.google.com"
          element = @driver.find_element(:name, 'q')
          element.send_keys "BrowserStack"
          element.submit
          assert_equal(@driver.title, "BrowserStack - Google Search")
        end
       
        def teardown
          @driver.quit
        end
      end
      
      
      parallel_test -n 2 test/google-search-browserstack-ie9.rb test/google-search-browserstack-chrome-mac.rb
      

      Note: When running parallel_test, the command can operate in one of two ways: 1) all the tests are passed to the command as parameters, with full pathnames; or 2) the current directory must have access to the test/ folder, so it finds the tests.

      Warning: parallel_test cannot be executed unless there are two or more tests in the folder.

      Cucumber

      Single test

      To start testing using Cucumber, you have to install the relevant dependencies.

      Show code snippet

        source 'http://rubygems.org'
        gem 'cucumber'
        gem 'selenium-webdriver'
        gem 'rspec'

      Next, define a features and a steps file, which together constitute your test.

      Feature: Google can search
      
      Background:
        Given I am on Google
      
      Scenario: Search for a term
        When I fill in "q" found by "name" with "BrowserStack"
        And I submit
        Then I should see title "BrowserStack - Google Search"
      
      Given /^I am on (.+)$/ do |url|
        @browser.navigate.to "http://www.google.com"
      end
      
      When /^I fill in "([^"]*)" found by "([^"]*)" with "([^"]*)"$/ do |value, type, keys|
        @element = @browser.find_element(type, value)
        @element.send_keys keys
      end
      
      When /^I submit$/ do
        @element.submit
      end
      
      Then /^I should see title "([^"]*)"$/ do |title|
        raise "Fail" if @browser.title != title
      end
      

      To get Cucumber to use the BrowserStack infrastructure, you will need to configure its capabilities accordingly, in the environment variable file, i.e. features/support/env.rb.

      require 'selenium/webdriver'
      
      url = "http://#{ENV['BS_USERNAME']}:#{ENV['BS_AUTHKEY']}@hub-cloud.browserstack.com/wd/hub"
      
      capabilities = Selenium::WebDriver::Remote::Capabilities.new
      
      capabilities['project'] = ENV['BS_AUTOMATE_PROJECT'] if ENV['BS_AUTOMATE_PROJECT']
      capabilities['build'] = ENV['BS_AUTOMATE_BUILD'] if ENV['BS_AUTOMATE_BUILD']
      
      if ENV['BS_AUTOMATE_OS']
        capabilities['os'] = ENV['BS_AUTOMATE_OS']
        capabilities['os_version'] = ENV['BS_AUTOMATE_OS_VERSION']
      else
        capabilities['platform'] = ENV['SELENIUM_PLATFORM'] || 'ANY'
      end
      
      capabilities['browser'] = ENV['SELENIUM_BROWSER'] || 'chrome'
      capabilities['browser_version'] = ENV['SELENIUM_VERSION'] if ENV['SELENIUM_VERSION']
      
      browser = Selenium::WebDriver.for(:remote, :url => url, :desired_capabilities => capabilities)
      
      Before do |scenario|
        @browser = browser
      end
      
      at_exit do
        browser.quit
      end
      

      Finally, run the test from the command-line interface, passing the parameters for the test environment.

      cucumber BS_USERNAME=USERNAME BS_AUTHKEY=ACCESS_KEY SELENIUM_PLATFORM=WINDOWS SELENIUM_BROWSER=chrome
      
      Parallel tests

      To start testing using Cucumber, you have to install the relevant dependencies.

      source 'http://rubygems.org'
      gem 'cucumber'
      gem 'selenium-webdriver'
      gem 'rspec'
      gem 'parallel'
            

      The browsers.json file defines the combinations on which the tests will be run.

      Warning: You need to use your username and password to access the browsers.json file.

      [
        {
          "browser": "firefox",
          "browser_version": "15.0",
          "device": null,
          "os": "OS X",
          "os_version": "Snow Leopard"
        },
        {
          "browser": "firefox",
          "browser_version": "16.0",
          "device": null,
          "os": "Windows",
          "os_version": "7"
        },
        {
          "browser": "firefox",
          "browser_version": "17.0",
          "device": null,
          "os": "Windows",
          "os_version": "8"
        },
        {
          "browser": "ie",
          "browser_version": "8.0",
          "device": null,
          "os": "Windows",
          "os_version": "7"
        },
        {
          "browser": "ie",
          "browser_version": "9.0",
          "device": null,
          "os": "Windows",
          "os_version": "7"
        },
        {
          "browser": "ie",
          "browser_version": "10.0",
          "device": null,
          "os": "Windows",
          "os_version": "8"
        }
      ]

      Next, define a features and a steps file, which together constitute your tests.

      Feature: Google can search
      
      Background:
        Given I am on Google
      
      Scenario: Search for a term
        When I fill in "q" found by "name" with "BrowserStack"
        And I submit
        Then I should see title "BrowserStack - Google Search"
      
      Given /^I am on (.+)$/ do |url|
        @browser.navigate.to "http://www.google.com"
      end
      
      When /^I fill in "([^"]*)" found by "([^"]*)" with "([^"]*)"$/ do |value, type, keys|
        @element = @browser.find_element(type, value)
        @element.send_keys keys
      end
      
      When /^I submit$/ do
        @element.submit
      end
      
      Then /^I should see title "([^"]*)"$/ do |title|
        raise "Fail" if @browser.title != title
      end
      

      Setup the username and access key environment variables, and the capabilities, to define the parameters for all the tests. Values will be passed to this via the command-line interface.

      require 'selenium/webdriver'
      
      url = "http://#{ENV['BS_USERNAME']}:#{ENV['BS_AUTHKEY']}@hub-cloud.browserstack.com/wd/hub"
      
      capabilities = Selenium::WebDriver::Remote::Capabilities.new
      capabilities['os'] = ENV['BS_AUTOMATE_OS']
      capabilities['os_version'] = ENV['BS_AUTOMATE_OS_VERSION']
      capabilities['browser'] = ENV['SELENIUM_BROWSER']
      capabilities['browser_version'] = ENV['SELENIUM_VERSION']
      capabilities['browserstack.debug'] = "true"
      
      capabilities['project'] = ENV['BS_AUTOMATE_PROJECT'] if ENV['BS_AUTOMATE_PROJECT']
      capabilities['build'] = ENV['BS_AUTOMATE_BUILD'] if ENV['BS_AUTOMATE_BUILD']
      
      browser = Selenium::WebDriver.for(:remote, :url => url,
                                        :desired_capabilities => capabilities)
      
      Before do |scenario|
        @browser = browser
      end
      
      at_exit do
        browser.quit
      end
      

      Create a Rakefile, which handles test management. If there are only three nodes available, for example, and the total number of tests exceeds that, then the Rakefile will schedule the tests to operate within those constraints.

      require 'rubygems'
      require 'cucumber'
      require 'cucumber/rake/task'
      require 'parallel'
      require 'json'
      
      @browsers = JSON.load(open('browsers.json'))
      @parallel_limit = ENV["nodes"] || 1
      @parallel_limit = @parallel_limit.to_i
      
      task :cucumber do
        Parallel.each(@browsers, :in_processes => @parallel_limit) do |browser|
          begin
            puts "Running with: #{browser.inspect}"
            ENV['SELENIUM_BROWSER'] = browser['browser']
            ENV['SELENIUM_VERSION'] = browser['browser_version']
            ENV['BS_AUTOMATE_OS'] = browser['os']
            ENV['BS_AUTOMATE_OS_VERSION'] = browser['os_version']
      
            Rake::Task[:run_features].execute()
          rescue Exception => e
            puts "Error while running task"
          end
        end
      end
      
      Cucumber::Rake::Task.new(:run_features)
      task :default => [:cucumber]
      

      Finally, run your tests by passing the username, access key, and number of parallel tests via the command-line interface.

      rake BS_USERNAME=USERNAME BS_AUTHKEY=ACCESS_KEY nodes=3
      

      Minitest

      Single test
      require 'rubygems'
      require 'minitest/autorun'
      require 'selenium-webdriver'
      
      class GoogleTest < MiniTest::Test
        USERNAME = ''
        BROWSERSTACK_ACCESS_KEY = ''
        def setup
          if USERNAME == ''
            puts "Please add USERNAME & BROWSERSTACK_ACCESS_KEY in this file"
            exit
          end
          url = "http://#{USERNAME}:#{BROWSERSTACK_ACCESS_KEY}@hub-cloud.browserstack.com/wd/hub"
          @driver = Selenium::WebDriver.for(:remote, :url => url)
        end
      
        def test_post
          @driver.navigate.to "http://www.google.com"
          element = @driver.find_element(:name, 'q')
          element.send_keys "BrowserStack"
          element.submit
          assert_equal(@driver.title, "BrowserStack - Google Search")
        end
      
        def teardown
          @driver.quit
        end
      end
      
      Parallel tests

      The browsers.json file defines the combinations on which the tests will be run.

      Warning: You need to use your username and password to access the browsers.json file.

      [
        {
          "browser": "firefox",
          "browser_version": "15.0",
          "device": null,
          "os": "OS X",
          "os_version": "Snow Leopard"
        },
        {
          "browser": "firefox",
          "browser_version": "16.0",
          "device": null,
          "os": "Windows",
          "os_version": "7"
        },
        {
          "browser": "firefox",
          "browser_version": "17.0",
          "device": null,
          "os": "Windows",
          "os_version": "8"
        },
        {
          "browser": "ie",
          "browser_version": "8.0",
          "device": null,
          "os": "Windows",
          "os_version": "7"
        },
        {
          "browser": "ie",
          "browser_version": "9.0",
          "device": null,
          "os": "Windows",
          "os_version": "7"
        },
        {
          "browser": "ie",
          "browser_version": "10.0",
          "device": null,
          "os": "Windows",
          "os_version": "8"
        }
      ]

      Setup the username and access key environment variables, and the capabilities, to define the parameters for all the tests. Values will be passed to this via the command-line interface.

      require 'rubygems'
      require 'minitest/autorun'
      require 'selenium-webdriver'
      
      class GoogleTest < MiniTest::Test
        USERNAME = ENV['BS_USERNAME']
        BROWSERSTACK_ACCESS_KEY = ENV['BS_AUTHKEY']
        
        def setup
          if USERNAME == ''
            puts "Please add username & key as parameters while running rake task"
            exit
          end
          url = "http://#{USERNAME}:#{BROWSERSTACK_ACCESS_KEY}@hub-cloud.browserstack.com/wd/hub"
          capabilities = Selenium::WebDriver::Remote::Capabilities.new
          capabilities['os'] = ENV['BS_AUTOMATE_OS']
          capabilities['os_version'] = ENV['BS_AUTOMATE_OS_VERSION']
          capabilities['browser'] = ENV['SELENIUM_BROWSER']
          capabilities['browser_version'] = ENV['SELENIUM_VERSION']
          @driver = Selenium::WebDriver.for(:remote,
                                            :url => url,
                                            :desired_capabilities => capabilities)
        end
       
        def test_post
          @driver.navigate.to "http://www.google.com"
          element = @driver.find_element(:name, 'q')
          element.send_keys "BrowserStack"
          element.submit
          assert_equal(@driver.title, "BrowserStack - Google Search")
        end
       
        def teardown
          @driver.quit
        end
      end
      
      

      Create a Rakefile, which handles test management. If there are only three nodes available, for example, and the total number of tests exceeds that, then the Rakefile will schedule the tests to operate within those constraints.

      require 'rubygems'
      require 'rake/testtask'
      require 'parallel'
      require 'json'
      
      @browsers = JSON.load(open('browsers.json'))
      @test_folder = "test/*_test.rb"
      @parallel_limit = ENV["nodes"] || 1
      @parallel_limit = @parallel_limit.to_i
      
      task :minitest do
        current_browser = ""
        begin
          Parallel.map(@browsers, :in_threads => @parallel_limit) do |browser|
            current_browser = browser
            puts "Running with: #{browser.inspect}"
            ENV['SELENIUM_BROWSER'] = browser['browser']
            ENV['SELENIUM_VERSION'] = browser['browser_version']
            ENV['BS_AUTOMATE_OS'] = browser['os']
            ENV['BS_AUTOMATE_OS_VERSION'] = browser['os_version']
            Dir.glob(@test_folder).each do |test_file|
              IO.popen("ruby #{test_file}") do |io|
                io.each do |line|
                  puts line
                end
              end
            end
          end
        rescue SystemExit, Interrupt
          puts "User stopped script!"
          puts "Failed to run tests for #{current_browser.inspect}"
        end
      end
      
      task :default => [:minitest]
      

      Finally, run your tests by passing the username, access key, and number of parallel tests via the command-line interface.

      rake BS_USERNAME=USERNAME BS_AUTHKEY=ACCESS_KEY nodes=3
      

      Watir

      To use Watir on BrowserStack, the tests must be configured to run on remote virtual machines. This is easily achieved by changing the capabilities of the webdriver. For instance, the following code would direct the webdriver to automate tests for Firefox on your local machine.

      browser = Watir::Browser.new(:firefox)
      

      Therefore, for the code to run on BrowserStack, the Watir capabilities have to be changed.

      browser = Watir::Browser.new(:remote,
        :url => "http://USERNAME:ACCESS_KEY@hub-cloud.browserstack.com/wd/hub",
        :desired_capabilities => caps)
      

      The example is a simple test made in Watir to run on Automate. It opens Google's homepage, searches for ‘browserstack’, and asks for the title of the search results page.

      require 'rubygems'
      require 'watir-webdriver'
      
      include Selenium
      
      caps = WebDriver::Remote::Capabilities.new
      caps[:os] = "Windows"
      caps[:name] = "Watir WebDriver"
      caps[:browser] = "firefox"
      caps[:browser_version] = "50"
      caps["browserstack.debug"] = "true"
      
      browser = Watir::Browser.new(:remote,
        :url => "http://USERNAME:ACCESS_KEY@hub-cloud.browserstack.com/wd/hub",
        :desired_capabilities => caps)
      
      browser.goto "http://www.google.com"
      browser.text_field(:name => 'q').set 'BrowserStack'
      browser.button(:name => 'btnK').click
      
      puts browser.title
      browser.quit
      

      Capybara

      Note: Check out our complete documentation for writing automate test scripts in Capybara.

      To integrate Capybara with BrowserStack infrastructure to run Cucumber tests, you will need to configure capabilities in the environment variable file.

      The following example configures the capabilities in features/support/env.rb:

      #features/sample.feature
      
      Feature: Google can search
      
      Background:
        Given I am on Google
      
      Scenario: Search for a term
        When I fill in "q" found by "name" with "BrowserStack"
        And I submit
        Then I should see title "BrowserStack - Google Search"
      
      #features/sample_steps.rb
      
      Given /^I am on (.+)$/ do |url|
        visit "/"
      end
       
      When /^I fill in "([^\"]*)" found by "([^\"]*)" with "([^\"]*)"$/ do |value, type, keys|
        fill_in(value, :with => keys)
      end
       
      When /^I submit$/ do
        find_field('q').native.send_key(:enter)
      end
       
      Then /^I should see title "([^\"]*)"$/ do |title|
        expect(page).to have_title title
      end
      
      #features/support/env.rb
      
      require 'selenium/webdriver'
      require 'capybara/cucumber'
      
      url = "http://#{ENV['BS_USERNAME']}:#{ENV['BS_AUTHKEY']}@hub-cloud.browserstack.com/wd/hub"
      
      Capybara.register_driver :browserstack do |app|
          capabilities = Selenium::WebDriver::Remote::Capabilities.new
      
          if ENV['BS_AUTOMATE_OS']
              capabilities['os'] = ENV['BS_AUTOMATE_OS']
              capabilities['os_version'] = ENV['BS_AUTOMATE_OS_VERSION']
          else
              capabilities['platform'] = ENV['SELENIUM_PLATFORM'] || 'ANY'
          end
      
          capabilities['browser'] = ENV['SELENIUM_BROWSER'] || 'chrome'
          capabilities['browser_version'] = ENV['SELENIUM_VERSION'] if ENV['SELENIUM_VERSION']
      
      
          capabilities['browserstack.debug'] = 'true'
          capabilities['project'] = ENV['BS_AUTOMATE_PROJECT'] if ENV['BS_AUTOMATE_PROJECT']
          capabilities['build'] = ENV['BS_AUTOMATE_BUILD'] if ENV['BS_AUTOMATE_BUILD']
      
          Capybara::Selenium::Driver.new(app,
                                       :browser => :remote, :url => url,
                                       :desired_capabilities => capabilities)
      end
      
      
      Capybara.default_driver = :browserstack
      Capybara.app_host = "http://www.google.com"
      Capybara.run_server = false
      

      Finally, run the test from the command-line interface, passing the parameters for the test environment.

      cucumber BS_USERNAME=USERNAME BS_AUTHKEY=ACCESS_KEY SELENIUM_PLATFORM=WINDOWS SELENIUM_BROWSER=chrome
      

      In This Article

      • Introduction
      • Prerequisites
      • Getting Started
      • Testing on Internal Networks
        • Getting Started
        • Multiple local testing connections
      • Configuring Capabilities
        • Run tests on desktop and mobile browsers
        • Builds and projects
        • Self-signed certificates
        • Enable and Disable Flash
        • Enable and Disable Pop-ups
        • Debugging
        • ChromeOptions
        • Firefox Profile
      • Speed up testing
        • Parallel tests
        • Queueing
        • Add-on
      • Advanced features
        • Taking screenshots
        • Basic HTTP Authentication
        • Uploads & Downloads
        • Session ID
        • Running tests from behind a proxy
        • REST API
      • Using testing frameworks
        • Test Unit
        • Cucumber
        • Minitest
        • Watir
        • Capybara

      Frameworks

      Capybara

      RSpec

      Related Articles

      Debugging Tools

      Browsers & Devices

      Capabilities

      Timeouts

      REST API

      JS Testing

      Local Testing

      Continuous Integration

      Travis CI

      TeamCity

      Products
      • Live
      • Automate
      • App Live New
      • App Automate New
      • Screenshots
      • Responsive
      • Enterprise
      Mobile
      • Test on Right Devices
      • Mobile Features
      • Mobile Emulators
      • Test on iPhone
      • Test on iPad
      • Test on Galaxy
      Other Links
      • Open Source
      • Test in IE
      • Careers We're hiring!
      • Support
      • Contact
      • Company
      • News
      Social
      Header logo

      © 2011-2018 BrowserStack - A cross-browser testing tool.

      • Terms of Service
      • Privacy Policy