Best Selenium code snippet using Selenium.WebDriver.Remote.close
driver.rb
Source:driver.rb
...99 # Use instance variable directly so we avoid starting the browser just to reset the session100 return unless @browser101 if firefox? || chrome?102 switch_to_window(window_handles.first)103 window_handles.slice(1..-1).each { |win| close_window(win) }104 end105 navigated = false106 start_time = Capybara::Helpers.monotonic_time107 begin108 unless navigated109 # Only trigger a navigation if we haven't done it already, otherwise it110 # can trigger an endless series of unload modals111 begin112 @browser.manage.delete_all_cookies113 clear_storage114 # rescue Selenium::WebDriver::Error::NoSuchAlertError115 # # Handle a bug in Firefox/Geckodriver where it thinks it needs an alert modal to exist116 # # for no good reason117 # retry118 rescue Selenium::WebDriver::Error::UnhandledError # rubocop:disable Lint/HandleExceptions119 # delete_all_cookies fails when we've previously gone120 # to about:blank, so we rescue this error and do nothing121 # instead.122 end123 @browser.navigate.to("about:blank")124 end125 navigated = true126 # Ensure the page is empty and trigger an UnhandledAlertError for any modals that appear during unload127 until find_xpath("/html/body/*").empty?128 raise Capybara::ExpectationNotMet, 'Timed out waiting for Selenium session reset' if (Capybara::Helpers.monotonic_time - start_time) >= 10129 sleep 0.05130 end131 rescue Selenium::WebDriver::Error::UnhandledAlertError, Selenium::WebDriver::Error::UnexpectedAlertOpenError132 # This error is thrown if an unhandled alert is on the page133 # Firefox appears to automatically dismiss this alert, chrome does not134 # We'll try to accept it135 begin136 @browser.switch_to.alert.accept137 sleep 0.25 # allow time for the modal to be handled138 rescue modal_error139 # The alert is now gone140 if current_url != "about:blank"141 begin142 # If navigation has not occurred attempt again and accept alert143 # since FF may have dismissed the alert at first attempt144 @browser.navigate.to("about:blank")145 sleep 0.1 # slight wait for alert146 @browser.switch_to.alert.accept147 rescue modal_error # rubocop:disable Metrics/BlockNesting, Lint/HandleExceptions148 # alert now gone, should mean navigation happened149 end150 end151 end152 # try cleaning up the browser again153 retry154 end155 end156 def switch_to_frame(frame)157 case frame158 when :top159 @frame_handles[browser.window_handle] = []160 browser.switch_to.default_content161 when :parent162 # would love to use browser.switch_to.parent_frame here163 # but it has an issue if the current frame is removed from within it164 @frame_handles[browser.window_handle].pop165 browser.switch_to.default_content166 @frame_handles[browser.window_handle].each { |fh| browser.switch_to.frame(fh) }167 else168 @frame_handles[browser.window_handle] ||= []169 @frame_handles[browser.window_handle] << frame.native170 browser.switch_to.frame(frame.native)171 end172 end173 def current_window_handle174 browser.window_handle175 end176 def window_size(handle)177 within_given_window(handle) do178 size = browser.manage.window.size179 [size.width, size.height]180 end181 end182 def resize_window_to(handle, width, height)183 within_given_window(handle) do184 # Don't set the size if already set - See https://github.com/mozilla/geckodriver/issues/643185 if marionette? && (window_size(handle) == [width, height])186 {}187 else188 browser.manage.window.resize_to(width, height)189 end190 end191 end192 def maximize_window(handle)193 within_given_window(handle) do194 browser.manage.window.maximize195 end196 sleep 0.1 # work around for https://code.google.com/p/selenium/issues/detail?id=7405197 end198 def close_window(handle)199 raise ArgumentError, "Not allowed to close the primary window" if handle == window_handles.first200 within_given_window(handle) do201 browser.close202 end203 end204 def window_handles205 browser.window_handles206 end207 def open_new_window208 browser.execute_script('window.open();')209 end210 def switch_to_window(handle)211 browser.switch_to.window handle212 end213 def accept_modal(_type, **options)214 yield if block_given?215 modal = find_modal(options)...
browser.rb
Source:browser.rb
...4 # require_relative 'phantomjs'5 #6 # Closes browser at the end of test.7 #8 def self.close_browser9 close_proxy10 @browser.close11 sleep 512 end13 #14 # Quits browser at the end of test without closing the window.15 #16 def self.quit_browser17 close_proxy18 @browser.quit19 sleep 520 end21 def self.is_first_visit_to_site?22 is_current_url_a_site_url? ? @is_first_visit_to_site : false23 end24 def self.is_current_url_a_site_url?25 #Current hostname == Site hostname26 ExecutionEnvironment.environment_name(@browser.current_url) == ExecutionEnvironment.host_name.split(/\./)[1]27 end28 def self.visited_site29 @is_first_visit_to_site = false30 end31 #32 # Restarts the browser in the middle of a test. The default is to not clear the browser's cookies.33 #34 def self.restart_browser(browser = ExecutionEnvironment.browser_name, clear_cookies = false, disable_cookies = false)35 BrowserHelper.close_popup(@browser)36 close_browser37 original_disable_cookies = @disable_cookies38 begin39 @disable_cookies = disable_cookies40 @browser = setup(browser, clear_cookies)41 ensure42 @disable_cookies = original_disable_cookies43 end44 end45 def self.close_proxy46 if ExecutionEnvironment.proxy_enabled? and @proxy_started47 ::CoreMetricsManager.instance.update_har_entries if ExecutionEnvironment.proxy_enabled?('CoreMetrics')48 @proxy_started = nil49 Proxy.close_proxy50 end51 end52 def self.start_proxy53 if ExecutionEnvironment.proxy_enabled? and !@proxy_started54 @proxy_started = Proxy::start_proxy.selenium_proxy(:http, :ssl)55 end56 @proxy_started57 end58 def self.proxy59 ExecutionEnvironment.proxy_enabled? ? start_proxy : false60 end61 #62 # Sets up a browser instance, enabling any necessary browser capabilities.63 # @param [Symbol] browser One of: :firefox, :chrome, :ie64 #65 def self.setup(browser = ExecutionEnvironment.browser_name, clear_cookies = true)66 p ExecutionEnvironment.browser_name67 @is_first_visit_to_site = true68 if ENV['MOBILE_WEB']69 @browser = setup_mobile70 @browser71 elsif browser == :none72 nil73 else74 if ExecutionEnvironment.digital_analytics_enabled?('plugin')75 if ExecutionEnvironment.host_os != :windows || ExecutionEnvironment.browser_name != :firefox76 raise("ERROR - ENV: Digital Analytics runs only on Windows and Firefox")77 end78 end79 begin80 if ExecutionEnvironment.reuse_browser?81 @browser_count ||= 082 # reuse the browser from the second one. The first one will be close shortly and never used83 if @browser_count < 284 @browser = self.send "setup_#{browser.to_s}"85 maximize_browser_window86 @browser_count += 187 end88 else89 @browser = self.send "setup_#{browser.to_s}"90 maximize_browser_window91 end92 @browser.manage.delete_all_cookies if clear_cookies unless ExecutionEnvironment.browser_name == :safari || :ie93 @browser94 rescue Timeout::Error95 raise $!, "Unable to acquire a(n) '#{browser.to_s}' browser session from the hub." if ExecutionEnvironment.selenium_grid_hub96 raise...
selenium_driver_setup.rb
Source:selenium_driver_setup.rb
...154 $app_host_and_port = "#{server_ip}:#{s.local_address.ip_port}"155 puts "found available port: #{$app_host_and_port}"156 return $server_port157 ensure158 s.close() if s159 end160 def self.start_webserver(webserver)161 setup_host_and_port162 case webserver163 when 'thin'164 self.start_in_process_thin_server165 when 'webrick'166 self.start_in_process_webrick_server167 else168 puts "no web server specified, defaulting to WEBrick"169 self.start_in_process_webrick_server170 end171 end172 def self.shutdown_webserver(server)173 shutdown = lambda do174 server.shutdown175 HostUrl.default_host = nil176 HostUrl.file_host = nil177 end178 at_exit { shutdown.call }179 return shutdown180 end181 def self.rack_app182 app = Rack::Builder.new do183 use Rails::Rack::Debugger unless Rails.env.test?184 run CanvasRails::Application185 end.to_app186 lambda do |env|187 nope = [503, {}, [""]]188 return nope unless allow_requests?189 # wrap request in a mutex so we can ensure it doesn't span spec190 # boundaries (see clear_requests!)191 result = request_mutex.synchronize { app.call(env) }192 # check if the spec just finished while we ran, and if so prevent193 # side effects like redirects (and thus moar requests)194 if allow_requests?195 result196 else197 # make sure we clean up the body of requests we throw away198 # https://github.com/rack/rack/issues/658#issuecomment-38476120199 result.last.close if result.last.respond_to?(:close)200 nope201 end202 end203 end204 class << self205 def disallow_requests!206 # ensure the current in-flight request (if any, AJAX or otherwise)207 # finishes up its work, and prevent any subsequent requests before the208 # next spec gets underway. otherwise race conditions can cause sadness209 # with our shared conn and transactional fixtures (e.g. special210 # accounts and their caching)211 @allow_requests = false212 request_mutex.synchronize { }213 end...
tryUsamp_lib.rb
Source:tryUsamp_lib.rb
...49 ff.text_field(:name, "txtEmail").set(email)50 ff.text_field(:name, "txtPassword").set(passwd)51 ff.button(:value,"login").click52 sleep 1553 if(ff.link(:id,"sb-nav-close").exists?)54 ff.link(:id,"sb-nav-close").click55 end56 sleep 557 58 if(ff.div(:id=>"loadingSurveys").exists?)59 while ff.div(:id=>"loadingSurveys").visible? do60 sleep 0.561 puts "waiting for surveys to load"62 end63 end64 65 raise("Sorry! System Failed to login to Usampadmin") unless ff.link(:text,'Logout').exists?66 return ff67 end68 69 # Method to login to sm.p.Surveyhead site70 # Parameters passed : email and password71 # Parameters returned : IE instance72 73 def Surveyhead_sm_login(email,passwd)74 75 # New IE instance creation76 driver = Selenium::WebDriver.for :firefox, :profile => "Selenium"77 ff = Watir::Browser.new driver78 #ff.maximize79 # Opening Usampadmin site80 ff.goto('http://www.sm.p.surveyhead.com')81 # Setting login credentials (email/password)82 ff.text_field(:name, "txtEmail").set(email)83 ff.text_field(:name, "txtPassword").set(passwd)84 #Click login button85 ff.button(:value, "Login").click86 sleep 1587 if(ff.link(:id,"sb-nav-close").exists?)88 ff.link(:id,"sb-nav-close").click89 end90 sleep 591 92 if(ff.div(:id=>"loadingSurveys").exists?)93 while ff.div(:id=>"loadingSurveys").visible? do94 sleep 0.595 puts "waiting for surveys to load"96 end97 end98 99 100 # Checkpoint to verify that login was successful101 raise("Sorry! System Failed to login to Usampadmin") unless ff.link(:text,'Logout').exists?102 return ff...
ChromeUsamp_lib.rb
Source:ChromeUsamp_lib.rb
...52 ff.text_field(:name, "txtEmail").set(email)53 ff.text_field(:name, "txtPassword").set(passwd)54 ff.button(:value,"login").click55 sleep 1556 if(ff.link(:id,"sb-nav-close").exists?)57 ff.link(:id,"sb-nav-close").click58 end59 sleep 560 61 if(ff.div(:id=>"loadingSurveys").exists?)62 while ff.div(:id=>"loadingSurveys").visible? do63 sleep 0.564 puts "waiting for surveys to load"65 end66 end67 68 raise("Sorry! System Failed to login to Usampadmin") unless ff.link(:text,'Logout').exists?69 return ff70 end71 72 # Method to login to sm.p.Surveyhead site73 # Parameters passed : email and password74 # Parameters returned : IE instance75 76 def Surveyhead_sm_login(email,passwd)77 78 # New IE instance creation79 #driver = Selenium::WebDriver.for :firefox, :profile => "Selenium"80 #ff = Watir::Browser.new driver81 ff = Watir::Browser.new :chrome82 #ff.maximize83 # Opening Usampadmin site84 ff.goto('http://www.sm.p.surveyhead.com')85 # Setting login credentials (email/password)86 ff.text_field(:name, "txtEmail").set(email)87 ff.text_field(:name, "txtPassword").set(passwd)88 #Click login button89 ff.button(:value, "Login").click90 sleep 1591 if(ff.link(:id,"sb-nav-close").exists?)92 ff.link(:id,"sb-nav-close").click93 end94 sleep 595 96 if(ff.div(:id=>"loadingSurveys").exists?)97 while ff.div(:id=>"loadingSurveys").visible? do98 sleep 0.599 puts "waiting for surveys to load"100 end101 end102 103 104 # Checkpoint to verify that login was successful105 raise("Sorry! System Failed to login to Usampadmin") unless ff.link(:text,'Logout').exists?106 return ff...
Usamp_lib.rb
Source:Usamp_lib.rb
...50 ff.text_field(:name, "txtEmail").set(email)51 ff.text_field(:name, "txtPassword").set(passwd)52 ff.button(:value,"Login").click53 sleep 1554 if(ff.link(:id,"sb-nav-close").exists?)55 ff.link(:id,"sb-nav-close").click56 end57 sleep 558 59 if(ff.div(:id=>"loadingSurveys").exists?)60 while ff.div(:id=>"loadingSurveys").visible? do61 sleep 0.562 puts "waiting for surveys to load"63 end64 end65 66 raise("Sorry! System Failed to login to Usampadmin") unless ff.link(:text,'Logout').exists?67 return ff68 end69 70 # Method to login to sm.p.Surveyhead site71 # Parameters passed : email and password72 # Parameters returned : IE instance73 74 def Surveyhead_sm_login(email,passwd)75 76 # New IE instance creation77 driver = Selenium::WebDriver.for :firefox, :profile => "Selenium"78 ff = Watir::Browser.new driver79 #ff.maximize80 # Opening Usampadmin site81 ff.goto('http://www.sm.p.surveyhead.com')82 # Setting login credentials (email/password)83 ff.text_field(:name, "txtEmail").set(email)84 ff.text_field(:name, "txtPassword").set(passwd)85 #Click login button86 ff.button(:value, "Login").click87 sleep 1588 if(ff.link(:id,"sb-nav-close").exists?)89 ff.link(:id,"sb-nav-close").click90 end91 sleep 592 93 if(ff.div(:id=>"loadingSurveys").exists?)94 while ff.div(:id=>"loadingSurveys").visible? do95 sleep 0.596 puts "waiting for surveys to load"97 end98 end99 100 101 # Checkpoint to verify that login was successful102 raise("Sorry! System Failed to login to Usampadmin") unless ff.link(:text,'Logout').exists?103 return ff...
watirspec_helper.rb
Source:watirspec_helper.rb
...106 @imp.guard_proc = lambda { |args|107 args.any? { |arg| matching_guards.include?(arg) }108 }109 ensure110 browser_instance.close if browser_instance111 end112 def firefox_args113 path = ENV['FIREFOX_BINARY']114 Selenium::WebDriver::Firefox::Binary.path = path if path115 {desired_capabilities: Selenium::WebDriver::Remote::Capabilities.firefox}116 end117 def ff_legacy_args118 @browser = :firefox119 @ff_legacy = true120 caps = Selenium::WebDriver::Remote::Capabilities.firefox(marionette: false)121 path = ENV['FF_LEGACY_BINARY']122 Selenium::WebDriver::Firefox::Binary.path = path if path123 {desired_capabilities: caps}124 end...
implementation.rb
Source:implementation.rb
...77 @imp.guard_proc = lambda { |args|78 args.any? { |arg| matching_guards.include?(arg) }79 }80 ensure81 browser_instance.close if browser_instance82 end83 def firefox_args84 profile = Selenium::WebDriver::Firefox::Profile.new85 profile.native_events = native_events?86 [:firefox, {:profile => profile}]87 end88 def chrome_args89 opts = {90 :args => ["--disable-translate"],91 :native_events => native_events?92 }93 if url = ENV['WATIR_WEBDRIVER_CHROME_SERVER']94 opts[:url] = url95 end96 if driver = ENV['WATIR_WEBDRIVER_CHROME_DRIVER']97 Selenium::WebDriver::Chrome.driver_path = driver98 end99 if path = ENV['WATIR_WEBDRIVER_CHROME_BINARY']100 Selenium::WebDriver::Chrome.path = path101 end102 if ENV['TRAVIS']103 opts[:args] << "--no-sandbox" # https://github.com/travis-ci/travis-ci/issues/938104 end105 [:chrome, opts]106 end107 def remote_args108 [:remote, {:url => ENV["WATIR_WEBDRIVER_REMOTE_URL"] || "http://127.0.0.1:8080"}]109 end110 def add_html_routes111 glob = File.expand_path("../html/*.html", __FILE__)112 Dir[glob].each do |path|113 WatirSpec::Server.get("/#{File.basename path}") { File.read(path) }114 end115 end116 def browser117 @browser ||= (ENV['WATIR_WEBDRIVER_BROWSER'] || :firefox).to_sym118 end119 def remote_browser120 remote_browser = WatirSpec.new_browser121 remote_browser.browser.name122 ensure123 remote_browser.close124 end125 def native_events?126 if ENV['NATIVE_EVENTS'] == "true"127 true128 elsif ENV['NATIVE_EVENTS'] == "false" && !ie?129 false130 else131 native_events_by_default?132 end133 end134 def native_events_by_default?135 Selenium::WebDriver::Platform.windows? && [:firefox, :internet_explorer].include?(browser)136 end137 class SelectorListener < Selenium::WebDriver::Support::AbstractEventListener...
Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!