How to close browser at the end of watir test suite?

10,349

Solution 1

When you want to use one and only browser during your RSpec specs, then you can use :suite hooks instead of :all which would create and close browser within each example group:

RSpec.configure do |config|
  config.before :suite do
    $browser = Watir::Browser.new
  end

  config.after :suite do
    $browser.close if $browser
  end
end

However, if for some strange reason you would not want to use RSpec or any test framework yourself then you can use Ruby's Kernel#at_exit method:

# somewhere
$browser = Watir::Browser.new
at_exit { $browser.close if $browser }

# other code, whenever needed
$browser.foo

I'd still recommend to use a testing framework and not create your own from scratch.

Solution 2

RSpec and Cucumber both have "after all" hooks.

RSpec:

describe "something" do
  before(:all) do
    @browser = Watir::Browser.new
  end
  after(:all) do
    @browser.close
  end
end

Cucumber in (env.rb):

browser = Watir::Browser.new

#teh codez

at_exit do
  browser.close
end
Share:
10,349
0xdabbad00
Author by

0xdabbad00

0xdabbad00.com icebuddha.com

Updated on June 12, 2022

Comments

  • 0xdabbad00
    0xdabbad00 almost 2 years

    Using ruby's watir to test a web app leaves the browser open at the end. Some advice online is that to make a true unit test you should open and close the browser on every test (in the teardown call), but that is slow and pointless. Or alternatively they do something like this:

     def self.suite
       s = super
       def s.afterClass
         # Close browser
       end
    
       def s.run(*args)
         super
         afterClass
       end
       s
     end
    

    but that causes the summary output to no longer display (Something like "100 tests, 100 assertions, 0 failures, 0 errors" should still display).

    How can I just get ruby or watir to close the browser at the end of my tests?

  • Jarmo Pertman
    Jarmo Pertman over 7 years
    @pguardiario global variable is necessary here because setting variables in :suite hooks in RSpec means that scope is different from all the examples/examplegroups. Also, using global variables for singleton objects (you only have one browser, right?) in places where it makes sense is not a shit hack. Or, how would you solve it?
  • pguardiario
    pguardiario over 7 years
    I don't really have anything better. Sorry, I'm deleting that comment.