Kyle
Kyle

Reputation: 4376

Handling browser closing when tests are done

I'm using Capybara with the Selenium webdriver in my testing suite. I've noticed that when all tests are complete, Selenium closes the browser by binding to at_exit. However, this causes an issue for my web application displays a "Are you sure you want to navigate away" dialog onunload (Please don't judge. This is an intranet application and the users specifically requested it.). So when the tests are done my Cucumber scenario fails (even though all my steps pass) because there was an unhandled Javascript confirm dialog. Is there any way to bind after Selenium tries to close the browser and accept the dialog?

Update

I believe I have found the issue with this. It appears that after each test, Capybara resets the browser by clearing all cookies and navigating to about:blank. This is what is causing the onbeforeunload dialog to open (not browser.quit()). I'm cross posting on the Capybara mailing list to try to get help on this and will post anything I find here.

Upvotes: 1

Views: 2465

Answers (4)

Kyle
Kyle

Reputation: 4376

As I mentioned in the OP update it appears that Capybara navigates to about:blank as the end of each Cucumber scenario. After talking with jnicklas from the Capybara team it appears that the best way to handle this is to implement a Cucumber after handler which navigates away before Capybara tries to and handle the alert there.

After do
  # after each test navigate away before Capybara tries to so that we can appropriately handle the onbeforeunload dialog
  if @browser
    begin
      @browser.navigate.to("about:blank")
      @browser.switch_to.alert.accept
    rescue Selenium::WebDriver::Error::NoAlertPresentError
      # No alert was present. Don't need to do anything
    end
  end
end

Upvotes: 0

Bala
Bala

Reputation: 11274

Is it possible for you to switch context at_exit and accept or dismiss the alert. Something like this

at_exit do
  page.driver.browser.switch_to.alert.accept
  #or
  page.driver.browser.switch_to.alert.dismiss
end

Upvotes: 1

djangofan
djangofan

Reputation: 29689

If you are using a unit test framework like JUnit or TestNG, then what I do is use Configuration annoations like @AfterTest or @AfterClass to quit the browser. This way, while the test is running the browser is always up. It's not until the @Test block is finished that the test case will close the browser instance.

If you are using Ruby, I assume there is something similar to this.

Upvotes: 0

Ben
Ben

Reputation: 667

Like it was mentioned, calling driver.Quit() should solve the problem, but if the pop-up window is causing an issue that prevents the browser from closing, then eliminate the instance. A simple solution is to wrap your test inside of a using clause.

using (IWebDriver driver = new FirefoxDriver())
{
    //Perform your test
    driver.Quit(); 
}

Upvotes: -1

Related Questions