title: Instantiating a watir browser on test failure in Cucumber without using the singleton pattern
body: <p>I've been trying to create a <a href="https://github.com/smoll/cucumber-seed" rel="nofollow">"cucumber seed" project</a> that I can use to quickly bootstrap a browser-based Acceptance Test suite. <a href="http://watirmelon.com/2012/04/01/five-page-object-anti-patterns/" rel="nofollow">Alister Scott has written</a> 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:</p>
  
  <pre><code>browser = Watir::Browser.new
  
  Before do
    @browser = browser
  end
  
  at_exit do
    browser.close
  end
  </code></pre>
  
  <p>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). </p>
  
  <p>My current approach is to wrap <code>Watir::Browser</code> instantiation in a <code>Browser</code> singleton class, like so:</p>
  
  <pre><code># support/browser.rb
  
  class Browser
    class &lt;&lt; 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
  </code></pre>
  
  <p>and then call it in my env.rb/hooks file like so:</p>
  
  <pre><code>Browser.start
  
  Before do
    @browser = Browser.instance
  end
  
  After do |scenario|
    Browser.restart if scenario.failed?
  end
  
  at_exit do
    Browser.stop
  end
  </code></pre>
  
  <p>Which works, but is there a better way to write this? Something that avoids having to use a singleton, perhaps?</p>