Search code examples
rubyseleniumcucumberselenium-webdriverautomated-tests

How to use same browser window for automated test using selenium-webdriver (ruby)?


I am automating test cases for a website using selenium-webdriver and cucumber in ruby. I need each feature to run in a particular order and using the same browser window. Atm each feature creates a new window to run test in. Though in some test cases this behavior is desired- in many cases it is not. From my research so far it seems there are mixed answers about whether or not it is possible to drive the same browser window with selenium throughout test cases. Most answers I have run into were for other languages and were work arounds specific to a browser (I am developing my test while testing IE but will be expected to run these test in other browsers). I am working in Ruby and from what I have read it seems as though I'd have to make a class for the page? I'm confused as to why I would have to do this or how that helps.

my env.rb file:

require 'selenium-webdriver'
require 'rubygems'
require 'nokogiri'
require 'rspec/expectations'

Before do

    @driver ||= Selenium::WebDriver.for :ie
    @accept_next_alert = true
    @driver.manage.timeouts.implicit_wait = 30
    @driver.manage.timeouts.script_timeout = 30
    @verification_errors = []
  end

  After do
    #@driver.quit
    #@verification_errors.should == []
  end

Some information I've gathered so far of people with similar problems: https://code.google.com/p/selenium/issues/detail?id=18 Is there any way to attach an already running browser to selenium webdriver in java?

Please ask me questions if anything about my question is not clear. I have many more test to create but I do not want to move on creating test if my foundation is sloppy and missing requested capabilities. (If you notice any other issues within my code please point them out in a comment)


Solution

  • The Before hook is run before each scenario. This is why a new browser is opened each time.

    Do the following instead (in the env.rb):

    require "selenium-webdriver"
    
    driver = Selenium::WebDriver.for :ie
    accept_next_alert = true
    driver.manage.timeouts.implicit_wait = 30
    driver.manage.timeouts.script_timeout = 30
    verification_errors = []
    
    Before do
      @driver = driver
    end
    
    at_exit do
      driver.close
    end
    

    In this case, a browser will be opened at the start (before any tests). Then each test will grab that browser and continue using it.

    Note: While it is usually okay to re-use the browser across tests. You should be careful about tests that need to be run in a specific order (ie become dependent). Dependent tests can be hard to debug and maintain.