Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 411
0xdabbad00 Avatar asked Jan 22 '13 13:01

0xdabbad00


2 Answers

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.

like image 58
Jarmo Pertman Avatar answered Oct 27 '22 03:10

Jarmo Pertman


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
like image 24
Željko Filipin Avatar answered Oct 27 '22 03:10

Željko Filipin