How to close browser at the end of watir test suite?
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
Comments
-
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 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 ashit hack
. Or, how would you solve it? -
pguardiario over 7 yearsI don't really have anything better. Sorry, I'm deleting that comment.