Selenium with RSpec

Note: Refer our sample repo on Github: rspec-browserstack

BrowserStack supports Selenium automated tests using RSpec, and running your tests on our cloud setup is simple and straightforward. Get started with a sample test, which opens Google’s homepage, searches for ‘BrowserStack’, and asserts for the title of the search results page. For the code to run successfully on your machine, please ensure that the following libraries have been installed:

# Install using gem
gem install rspec

Run your first test

Here is a sample test case written for running with RSpec.

describe "Google's Search Functionality" do
  it "can find search results" do
    @driver.navigate.to "https://www.google.com/ncr"
    element = @driver.find_element(:name, 'q')
    element.send_keys "BrowserStack"
    element.submit
    sleep 5
    expect(@driver.title).to eql("BrowserStack - Google Search")
  end
end

To actually run the test case, we need to integrate with BrowserStack as follows.

Integration with BrowserStack

Integration of RSpec with BrowserStack is made possible by use of following module:

require 'yaml'
require 'rspec'
require 'selenium-webdriver'
require 'browserstack/local'

TASK_ID = (ENV['TASK_ID'] || 0).to_i
CONFIG_NAME = ENV['CONFIG_NAME'] || 'single'

CONFIG = YAML.load(File.read(File.join(File.dirname(__FILE__), "../config/#{CONFIG_NAME}.config.yml")))
CONFIG['user'] = ENV['BROWSERSTACK_USERNAME'] || CONFIG['user']
CONFIG['key'] = ENV['BROWSERSTACK_ACCESS_KEY'] || CONFIG['key']


RSpec.configure do |config|
  config.around(:example) do |example|
    @caps = CONFIG['common_caps'].merge(CONFIG['browser_caps'][TASK_ID])
    @caps["name"] = ENV['name'] || example.metadata[:name] || example.metadata[:file_path].split('/').last.split('.').first
    enable_local = @caps["browserstack.local"] && @caps["browserstack.local"].to_s == "true"

    # Code to start browserstack local before start of test
    if enable_local
      @bs_local = BrowserStack::Local.new
      bs_local_args = { "key" => CONFIG['key'], "forcelocal" => true }
      @bs_local.start(bs_local_args)
      @caps["browserstack.local"] = true
    end

    @driver = Selenium::WebDriver.for(:remote,
      :url => "https://#{CONFIG['user']}:#{CONFIG['key']}@#{CONFIG['server']}/wd/hub",
      :desired_capabilities => @caps)

    begin
      example.run
    ensure
      @driver.quit
      # Code to stop browserstack local after end of test
      @bs_local.stop if enable_local
    end
  end
end

The module reads from config file where you need to put the BrowserStack Hub URL and credentials.

server: "hub-cloud.browserstack.com"
user: "YOUR_USERNAME"
key: "YOUR_ACCESS_KEY"

common_caps:
  "browserstack.debug": true
  "name": "Bstack-[Rspec] Sample Test"

browser_caps:
  -
    "browser": "chrome"

Run your test on BrowserStack using following command:

# Run using rake
bundle exec rake single

Configuring capabilities

To run your tests on BrowserStack Automate, the tests have to be run on remote machines. Therefore, the capabilities of the WebDriver have to be changed accordingly.

Run tests on desktop and mobile browsers

Using the drop-down menus, select a combination of operating system, browser, and screen resolution. To see the order of precedence for the capabilities, please read about parameter override rules here.

You can additionally run your Selenium test scripts on real Android and iOS devices in our datacenters.

Look for the icon to select a real device.

 

Note: If browser_version capability is not set, the test will run on the latest version of the browser set by browser capability.

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.

 common_caps:
  "build": "version1"
  "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.

common_caps:
  "acceptSslCerts": true

Enable and Disable Pop-ups

  • IE

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

common_caps:
  "browserstack.ie.enablePopups": true
  • Safari

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

common_caps:
  "browserstack.safari.enablePopups": true

Debugging

  • Logs

To debug failed tests, BrowserStack provides you with raw logs, which are the console logs from the browser tests; visual logs, which capture successive screenshots of the test; and text logs to display all the steps that were performed by the test.

  • Live screencast

With live screencast, view ongoing tests to debug the functionality of features that are being tested. The generated videos can be recorded and downloaded for later viewing.

Logs and the live screencast help you to compare and detect any changes that may have occurred since a similar test was last run. Debugging is set to false by default. To enable logs, set the BrowserStack custom capability browserstack.debug to true.

common_caps:
  "browserstack.debug": true
  • Video recording Videos are recorded for every BrowserStack Automate test. This feature helps you to verify and debug failed tests, confirm the functionality of tested features, and download videos for later viewing.

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

common_caps:
  "browserstack.video": false

Other capabilities

BrowserStack supports the full complement of Selenium capabilities, as well as, some custom ones.

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://YOUR_USERNAME:YOUR_ACCESS_KEY@api.browserstack.com/automate/sessions/<session-id>.json', {"status"=>"completed", "reason"=>""}, {:content_type => :json}

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

Queuing

With queuing, you can launch an additional number of parallel tests with different browser configurations that will be queued in a sequence, for a seamless parallel execution. 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 can be less bothered about managing your tests, and it can save development time.

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.