Reputation: 998
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?
Upvotes: 6
Views: 10926
Reputation: 1905
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.
Upvotes: 12
Reputation: 57322
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
Upvotes: 2