Prevent closure of primary window in Selenium driver

This commit is contained in:
Thomas Walpole 2018-03-15 12:48:19 -07:00
parent f2a431931f
commit d1089ef2c7
3 changed files with 15 additions and 4 deletions

View File

@ -26,6 +26,8 @@ class Capybara::Selenium::Driver < Capybara::Driver::Base
@w3c = ((defined?(Selenium::WebDriver::Remote::W3CCapabilities) && @browser.capabilities.is_a?(Selenium::WebDriver::Remote::W3CCapabilities)) ||
(defined?(Selenium::WebDriver::Remote::W3C::Capabilities) && @browser.capabilities.is_a?(Selenium::WebDriver::Remote::W3C::Capabilities)))
main = Process.pid
@primary_window_handle = current_window_handle
at_exit do
# Store the exit status of the test run since it goes away after calling the at_exit proc...
@exit_status = $ERROR_INFO.status if $ERROR_INFO.is_a?(SystemExit)
@ -108,7 +110,8 @@ class Capybara::Selenium::Driver < Capybara::Driver::Base
# Use instance variable directly so we avoid starting the browser just to reset the session
return unless @browser
window_handles.reject { |handle| handle == current_window_handle }.each { |win| close_window(win) }
switch_to_window(@primary_window_handle)
window_handles.reject { |handle| handle == @primary_window_handle }.each { |win| close_window(win) }
navigated = false
start_time = Capybara::Helpers.monotonic_time
@ -207,6 +210,7 @@ class Capybara::Selenium::Driver < Capybara::Driver::Base
end
def close_window(handle)
raise ArgumentError, "Not allowed to close the primary window" if handle == @primary_window_handle
within_given_window(handle) do
browser.close
end

View File

@ -20,16 +20,15 @@ Capybara::SpecHelper.spec '#within_window', requires: [:windows] do
context "with an instance of Capybara::Window" do
it "should not invoke driver#switch_to_window when given current window" do
# switch_to_window is invoked in after hook
expect(@session.driver).to receive(:switch_to_window).exactly(3).times.and_call_original
allow(@session.driver).to receive(:switch_to_window).and_call_original
@session.within_window @window do
expect(@session.title).to eq('With Windows')
end
expect(@session.driver).not_to have_received(:switch_to_window)
end
it "should be able to switch to another window" do
window = (@session.windows - [@window]).first
expect(@session.driver).to receive(:switch_to_window).exactly(5).times.and_call_original
@session.within_window window do
expect(@session).to have_title(/Title of the first popup|Title of popup two/)
end

View File

@ -217,5 +217,13 @@ RSpec.shared_examples "Capybara::Session" do |session, mode|
expect(@session).to have_current_path('/')
end
end
context "Windows" do
it "can't close the primary window" do
expect do
@session.current_window.close
end.to raise_error(ArgumentError, 'Not allowed to close the primary window')
end
end
end
end