Zack
Zack

Reputation: 2497

Capybara session not closing at end of test

I have a series of automated tests using selenium/capybara/rspec. For one of my tests, I am dirtying a form and verifying that certain errors are triggered. That is the end of the test... The problem is that when the test finishes running, the and the code tries to close the browser, a JavaScript message pops up with This page is asking you to confirm that you want to leave - data you have entered may not be saved.

In my spec helper I have:

Capybara.register_driver :firefox do |app|
  Capybara::Selenium::Driver.new(app, browser: :firefox)
end

Capybara.default_driver = :firefox
Capybara.app_host = ********* #redacted
Capybara.default_max_wait_time = 5

RSpec.configure do |config|
  config.before(:each) do
    config.include Capybara::DSL
  end

  config.after(:each) do
    Capybara.reset_sessions!
  end
end

and am getting a test failure with Capybara::ExpectationNotMet: Timed out waiting for Selenium session reset

How do I make the test close the browser at the end?

Upvotes: 1

Views: 1344

Answers (1)

Thomas Walpole
Thomas Walpole

Reputation: 49950

You don't indicate what browser and version of the browser you're using (for instance FF 59 has recently made a change that makes handling unload modals more difficultg to deal with) nor any other versions of the test gems you're using, so it's tough to say whether or not your current issue would be fixed by upgrading (it may). However you can work around this issue in the tests where you know an unload modal will appear by adding

accept_confirm do
  visit("about:blank") # or any page in your app that doesn't have an unload modal ( / for instance )
end

to the end of those specific tests. That could be implemented in after block triggered by metadata on the feature if you want to keep your actual test code clean. To implement it via metadata you'd change your RSpec configure block to something like

RSpec.configure do |config|
  config.before(:each) do
    config.include Capybara::DSL
  end

  config.after(:each, clear_unload_modal: true) do
    accept_confirm do # may need to be Capybara.current_session.accept_confirm depending on your includes
      visit("/") # may need to be Capybara.current_session.visit
    end
  end

  config.after(:each) do
    Capybara.reset_sessions!
  end
end

and then tag each test that needs it with :clear_unload_modal

scenario "blah blah", :clear_unload_modal do
  ....
end

Upvotes: 1

Related Questions