简体   繁体   中英

Instantiating a watir browser on test failure in Cucumber without using the singleton pattern

I've been trying to create a "cucumber seed" project that I can use to quickly bootstrap a browser-based Acceptance Test suite. Alister Scott has written about a common antipattern of constantly closing and reopening browser windows (which adds unnecessary delay to a test suite), which can be avoided by adding the following to the env.rb file:

browser = Watir::Browser.new

Before do
  @browser = browser
end

at_exit do
  browser.close
end

But I'm unsure of how to incorporate this behavior, while still restarting the browser when a test fails (this ensures that a failed test does not leak browser state and cause a cascade of failures to unrelated scenarios).

My current approach is to wrap Watir::Browser instantiation in a Browser singleton class, like so:

# support/browser.rb

class Browser
  class << self
    def instance
      @browser
    end

    def start(name: 'chrome')
      @name = name
      @browser = Watir::Browser.new(name.to_sym)
    end

    def stop
      @browser.close # if a page hangs this will fail with a selenium unknown error
    rescue Selenium::WebDriver::Error
      puts 'Failed to close old browser (possibly because page is hanging), starting new one!'
    end

    def restart
      stop
      start(name: @name)
    end
  end # singleton methods
end

and then call it in my env.rb/hooks file like so:

Browser.start

Before do
  @browser = Browser.instance
end

After do |scenario|
  Browser.restart if scenario.failed?
end

at_exit do
  Browser.stop
end

Which works, but is there a better way to write this? Something that avoids having to use a singleton, perhaps?

I don't think this approach would be useful if the application is not stable. I would suggest creating a new instance of browser and closing it at the end of scenario.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM