Best Selenium code snippet using Selenium.WebDriver.wait
driver.rb
Source:driver.rb
...75 end76 def find_css(selector)77 browser.find_elements(:css, selector).map { |node| Capybara::Selenium::Node.new(self, node) }78 end79 def wait?; true; end80 def needs_server?; true; end81 def execute_script(script, *args)82 browser.execute_script(script, *args.map { |arg| arg.is_a?(Capybara::Selenium::Node) ? arg.native : arg} )83 end84 def evaluate_script(script, *args)85 result = execute_script("return #{script}", *args)86 unwrap_script_result(result)87 end88 def save_screenshot(path, _options={})89 browser.save_screenshot(path)90 end91 def reset!92 # Use instance variable directly so we avoid starting the browser just to reset the session93 if @browser94 navigated = false95 start_time = Capybara::Helpers.monotonic_time96 begin97 if !navigated98 # Only trigger a navigation if we haven't done it already, otherwise it99 # can trigger an endless series of unload modals100 begin101 @browser.manage.delete_all_cookies102 if options[:clear_session_storage]103 if @browser.respond_to? :session_storage104 @browser.session_storage.clear105 else106 warn "sessionStorage clear requested but is not available for this driver"107 end108 end109 if options[:clear_local_storage]110 if @browser.respond_to? :local_storage111 @browser.local_storage.clear112 else113 warn "localStorage clear requested but is not available for this driver"114 end115 end116 rescue Selenium::WebDriver::Error::UnhandledError117 # delete_all_cookies fails when we've previously gone118 # to about:blank, so we rescue this error and do nothing119 # instead.120 end121 @browser.navigate.to("about:blank")122 end123 navigated = true124 #Ensure the page is empty and trigger an UnhandledAlertError for any modals that appear during unload125 until find_xpath("/html/body/*").empty? do126 raise Capybara::ExpectationNotMet.new('Timed out waiting for Selenium session reset') if (Capybara::Helpers.monotonic_time - start_time) >= 10127 sleep 0.05128 end129 rescue Selenium::WebDriver::Error::UnhandledAlertError, Selenium::WebDriver::Error::UnexpectedAlertOpenError130 # This error is thrown if an unhandled alert is on the page131 # Firefox appears to automatically dismiss this alert, chrome does not132 # We'll try to accept it133 begin134 @browser.switch_to.alert.accept135 sleep 0.25 # allow time for the modal to be handled136 rescue Selenium::WebDriver::Error::NoAlertPresentError137 # The alert is now gone - nothing to do138 end139 # try cleaning up the browser again140 retry141 end142 end143 end144 def switch_to_frame(frame)145 case frame146 when :top147 @frame_handles[browser.window_handle] = []148 browser.switch_to.default_content149 when :parent150 # would love to use browser.switch_to.parent_frame here151 # but it has an issue if the current frame is removed from within it152 @frame_handles[browser.window_handle].pop153 browser.switch_to.default_content154 @frame_handles[browser.window_handle].each { |fh| browser.switch_to.frame(fh) }155 else156 @frame_handles[browser.window_handle] ||= []157 @frame_handles[browser.window_handle] << frame.native158 browser.switch_to.frame(frame.native)159 end160 end161 def current_window_handle162 browser.window_handle163 end164 def window_size(handle)165 within_given_window(handle) do166 size = browser.manage.window.size167 [size.width, size.height]168 end169 end170 def resize_window_to(handle, width, height)171 within_given_window(handle) do172 # Don't set the size if already set - See https://github.com/mozilla/geckodriver/issues/643173 if marionette? && (window_size(handle) == [width, height])174 {}175 else176 browser.manage.window.resize_to(width, height)177 end178 end179 end180 def maximize_window(handle)181 within_given_window(handle) do182 browser.manage.window.maximize183 end184 sleep 0.1 # work around for https://code.google.com/p/selenium/issues/detail?id=7405185 end186 def close_window(handle)187 within_given_window(handle) do188 browser.close189 end190 end191 def window_handles192 browser.window_handles193 end194 def open_new_window195 browser.execute_script('window.open();')196 end197 def switch_to_window(handle)198 browser.switch_to.window handle199 end200 def within_window(locator)201 handle = find_window(locator)202 browser.switch_to.window(handle) { yield }203 end204 def accept_modal(_type, options={})205 if headless_chrome?206 insert_modal_handlers(true, options[:with], options[:text])207 yield if block_given?208 find_headless_modal(options)209 else210 yield if block_given?211 modal = find_modal(options)212 modal.send_keys options[:with] if options[:with]213 message = modal.text214 modal.accept215 message216 end217 end218 def dismiss_modal(_type, options={})219 if headless_chrome?220 insert_modal_handlers(false, options[:with], options[:text])221 yield if block_given?222 find_headless_modal(options)223 else224 yield if block_given?225 modal = find_modal(options)226 message = modal.text227 modal.dismiss228 message229 end230 end231 def quit232 @browser.quit if @browser233 rescue Errno::ECONNREFUSED234 # Browser must have already gone235 rescue Selenium::WebDriver::Error::UnknownError => e236 unless silenced_unknown_error_message?(e.message) # Most likely already gone237 # probably already gone but not sure - so warn238 warn "Ignoring Selenium UnknownError during driver quit: #{e.message}"239 end240 ensure241 @browser = nil242 end243 def invalid_element_errors244 [::Selenium::WebDriver::Error::StaleElementReferenceError,245 ::Selenium::WebDriver::Error::UnhandledError,246 ::Selenium::WebDriver::Error::ElementNotVisibleError,247 ::Selenium::WebDriver::Error::InvalidSelectorError, # Work around a race condition that can occur with chromedriver and #go_back/#go_forward248 ::Selenium::WebDriver::Error::ElementNotInteractableError,249 ::Selenium::WebDriver::Error::ElementClickInterceptedError]250 end251 def no_such_window_error252 Selenium::WebDriver::Error::NoSuchWindowError253 end254 # @api private255 def marionette?256 firefox? && browser && @w3c257 end258 # @api private259 def firefox?260 browser_name == "firefox"261 end262 # @api private263 def chrome?264 browser_name == "chrome"265 end266 # @api private267 def headless_chrome?268 if chrome?269 caps = @processed_options[:desired_capabilities]270 chrome_options = caps[:chrome_options] || caps[:chromeOptions] || {}271 args = chrome_options['args'] || chrome_options[:args] || []272 return args.include?("headless")273 end274 return false275 end276 # @deprecated This method is being removed277 def browser_initialized?278 super && !@browser.nil?279 end280 private281 # @api private282 def browser_name283 options[:browser].to_s284 end285 def find_window(locator)286 handles = browser.window_handles287 return locator if handles.include? locator288 original_handle = browser.window_handle289 handles.each do |handle|290 switch_to_window(handle)291 if (locator == browser.execute_script("return window.name") ||292 browser.title.include?(locator) ||293 browser.current_url.include?(locator))294 switch_to_window(original_handle)295 return handle296 end297 end298 raise Capybara::ElementNotFound, "Could not find a window identified by #{locator}"299 end300 def insert_modal_handlers(accept, response_text, expected_text=nil)301 script = <<-JS302 if (typeof window.capybara === 'undefined') {303 window.capybara = {304 modal_handlers: [],305 current_modal_status: function() {306 return [this.modal_handlers[0].called, this.modal_handlers[0].modal_text];307 },308 add_handler: function(handler) {309 this.modal_handlers.unshift(handler);310 },311 remove_handler: function(handler) {312 window.alert = handler.alert;313 window.confirm = handler.confirm;314 window.prompt = handler.prompt;315 },316 handler_called: function(handler, str) {317 handler.called = true;318 handler.modal_text = str;319 this.remove_handler(handler);320 }321 };322 };323 var modal_handler = {324 prompt: window.prompt,325 confirm: window.confirm,326 alert: window.alert,327 called: false328 }329 window.capybara.add_handler(modal_handler);330 window.alert = window.confirm = function(str) {331 window.capybara.handler_called(modal_handler, str);332 return #{accept ? 'true' : 'false'};333 };334 window.prompt = function(str) {335 window.capybara.handler_called(modal_handler, str);336 return #{accept ? "'#{response_text}'" : 'null'};337 }338 JS339 execute_script script340 end341 def within_given_window(handle)342 original_handle = self.current_window_handle343 if handle == original_handle344 yield345 else346 switch_to_window(handle)347 result = yield348 switch_to_window(original_handle)349 result350 end351 end352 def find_modal(options={})353 # Selenium has its own built in wait (2 seconds)for a modal to show up, so this wait is really the minimum time354 # Actual wait time may be longer than specified355 wait = Selenium::WebDriver::Wait.new(356 timeout: options.fetch(:wait, session_options.default_max_wait_time) || 0 ,357 ignore: Selenium::WebDriver::Error::NoAlertPresentError)358 begin359 wait.until do360 alert = @browser.switch_to.alert361 regexp = options[:text].is_a?(Regexp) ? options[:text] : Regexp.escape(options[:text].to_s)362 alert.text.match(regexp) ? alert : nil363 end364 rescue Selenium::WebDriver::Error::TimeOutError365 raise Capybara::ModalNotFound.new("Unable to find modal dialog#{" with #{options[:text]}" if options[:text]}")366 end367 end368 def find_headless_modal(options={})369 # Selenium has its own built in wait (2 seconds)for a modal to show up, so this wait is really the minimum time370 # Actual wait time may be longer than specified371 wait = Selenium::WebDriver::Wait.new(372 timeout: options.fetch(:wait, session_options.default_max_wait_time) || 0 ,373 ignore: Selenium::WebDriver::Error::NoAlertPresentError)374 begin375 wait.until do376 called, alert_text = evaluate_script('window.capybara && window.capybara.current_modal_status()')377 if called378 execute_script('window.capybara && window.capybara.modal_handlers.shift()')379 regexp = options[:text].is_a?(Regexp) ? options[:text] : Regexp.escape(options[:text].to_s)380 if alert_text.match(regexp)381 alert_text382 else383 raise Capybara::ModalNotFound.new("Unable to find modal dialog#{" with #{options[:text]}" if options[:text]}")384 end385 elsif called.nil?386 # page changed so modal_handler data has gone away387 warn "Can't verify modal text when page change occurs - ignoring" if options[:text]388 ""389 else...
selenium_element_spec.rb
Source:selenium_element_spec.rb
...62 @selenium_driver.should_receive(:context_click)63 @selenium_element.right_click64 end65 it "should be able to block until it is present" do66 wait = double('wait')67 ::Selenium::WebDriver::Wait.should_receive(:new).and_return(wait)68 wait.should_receive(:until)69 @selenium_element.when_present(10)70 end71 72 it "should return the element when it is present" do73 wait = double('wait')74 ::Selenium::WebDriver::Wait.should_receive(:new).and_return(wait)75 wait.should_receive(:until)76 element = @selenium_element.when_present(10)77 element.should === @selenium_element78 end79 it "should return when an element is not present" do80 wait = double('wait')81 ::Selenium::WebDriver::Wait.should_receive(:new).and_return(wait)82 wait.should_receive(:until)83 @selenium_element.when_not_present84 end85 it "should be able to block until it is visible" do86 wait = double('wait')87 ::Selenium::WebDriver::Wait.should_receive(:new).and_return(wait)88 wait.should_receive(:until)89 @selenium_element.when_visible(10)90 end91 92 it "should return the element when it is visible" do93 wait = double('wait')94 ::Selenium::WebDriver::Wait.should_receive(:new).and_return(wait)95 wait.should_receive(:until)96 element = @selenium_element.when_visible(10)97 element.should === @selenium_element98 end99 it "should be able to block until it is not visible" do100 wait = double('wait')101 ::Selenium::WebDriver::Wait.should_receive(:new).and_return(wait)102 wait.should_receive(:until)103 @selenium_element.when_not_visible(10)104 end105 it "should return the element when it is not visible" do106 wait = double('wait')107 ::Selenium::WebDriver::Wait.should_receive(:new).and_return(wait)108 wait.should_receive(:until)109 element = @selenium_element.when_not_visible(10)110 element.should === @selenium_element111 end112 it "should be able to block until a user define event fires true" do113 wait = double('wait')114 ::Selenium::WebDriver::Wait.should_receive(:new).and_return(wait)115 wait.should_receive(:until)116 @selenium_element.wait_until(10, "Element blah") {}117 end118 it "should send keys to the element" do119 @selenium_driver.should_receive(:send_keys).with([:control, 'a'])120 @selenium_element.send_keys([:control, 'a'])121 end122 123 it "should clear its' contents" do124 @selenium_driver.should_receive(:clear)125 @selenium_element.clear126 end127 it "should fire an event" do128 @selenium_driver.should_receive(:instance_variable_get).with(:@bridge).and_return(@selenium_driver)129 @selenium_driver.should_receive(:executeScript)130 @selenium_element.fire_event('onfocus')...
wait
Using AI Code Generation
1wait = Selenium::WebDriver::Wait.new(:timeout => 10)2element = wait.until { driver.find_element(:id => "hplogo") }3wait = Selenium::WebDriver::Wait.new(:timeout => 10)4wait.until { driver.find_element(:id => "hplogo") }5wait = Selenium::WebDriver::Wait.new(:timeout => 10)6wait.until { driver.find_element(:id => "hplogos") }7wait = Selenium::WebDriver::Wait.new(:timeout => 10)8wait.until { driver.find_element(:id => "hplogos") }9wait = Selenium::WebDriver::Wait.new(:timeout => 10)10wait.until { driver.find_element(:id => "hplogo") }11wait = Selenium::WebDriver::Wait.new(:timeout => 10)12wait.until { driver.find_element(:id => "hplogo") }
wait
Using AI Code Generation
1driver.find_element(:name, 'q').send_keys "Selenium WebDriver"2driver.find_element(:name, 'btnG').click3driver.find_element(:link, 'Selenium - Web Browser Automation').click4driver.find_element(:name, 'q').send_keys "Selenium WebDriver"5driver.find_element(:name, 'btnG').click
wait
Using AI Code Generation
1element = driver.find_element(:name, 'q')2wait.until { driver.title.downcase.start_with? "selenium webdriver" }3element = driver.find_element(:name, 'q')4wait.until { driver.title.downcase.start_with? "selenium webdriver" }5element = driver.find_element(:name, 'q')6wait.until { driver.title.downcase.start_with? "selenium webdriver" }7element = driver.find_element(:name, 'q')8wait.until { driver.title.downcase.start_with? "selenium webdriver" }9element = driver.find_element(:name, 'q')10wait.until { driver.title.downcase.start_with? "selenium webdriver
wait
Using AI Code Generation
1search_box = driver.find_element(:name, 'q')2wait.until { driver.title.downcase.start_with? "selenium webdriver" }3search_box = driver.find_element(:name, 'q')4wait.until { driver.title.downcase.start_with? "selenium webdriver" }5search_box = driver.find_element(:name, 'q')6wait.until { driver.title.downcase.start_with? "selenium webdriver" }, "Title did not start with 'Selenium WebDriver'"7search_box = driver.find_element(:name, 'q')8 wait.until { driver.title.downcase.start_with? "selenium webdriver" }, "Title did not start with 'Selenium WebDriver'"
wait
Using AI Code Generation
1element = driver.find_element(:name, 'q')2element = wait.until { driver.find_element(:name, 'q') }3element = wait.until { driver.find_element(:name, 'q') }4element = wait.until { driver.find_element(:name, 'q') }5element = wait.until { driver.find_element(:name, 'q') }
wait
Using AI Code Generation
1driver.find_element(:name, 'q').send_keys "Selenium WebDriver"2driver.find_element(:name, 'btnG').click3element = driver.find_element(:name, 'q')4wait = Selenium::WebDriver::Wait.new(:timeout => 10)5wait.until { element.displayed? }6wait = Selenium::WebDriver::Wait.new(:timeout => 10)7wait.until { driver.find_element(:name, 'q').displayed? }8driver.find_element(:name, 'q').send_keys "Selenium WebDriver"9driver.find_element(:name, 'btnG').click10wait = Selenium::WebDriver::Wait.new(:timeout => 10)11wait.until { driver.find_element(:name, 'q').displayed? }12element = driver.find_element(:name, 'q')13wait = Selenium::WebDriver::Wait.new(:timeout => 10)14wait.until { driver.find_element(:name, 'q').displayed? }15driver.find_element(:name, 'q').send_keys "Selenium WebDriver"16driver.find_element(:name, 'btnG').click17wait.until { driver.find_element(:id, 'resultStats').displayed? }
wait
Using AI Code Generation
1driver.find_element(:name, 'q').send_keys "selenium tutorial"2driver.find_element(:name, 'btnK').click3driver.find_element(:link, 'Selenium Tutorial').click
wait
Using AI Code Generation
1element = driver.find_element(:name, 'q')2wait.until {driver.title.downcase.start_with? "hello"}3element = driver.find_element(:name, 'q')4wait.until {driver.title.downcase.start_with? "hello"}5element = driver.find_element(:name, 'q')6wait.until {driver.title.downcase.start_with? "hello"}7element = driver.find_element(:name, 'q')8element = wait.until { driver.find_element(:name, 'q') }9element = wait.until { driver.find_element(:name, 'q') }10element = wait.until { driver.find_element(:name, 'q') }11element = wait.until { driver.find_element(:name, 'q') }
wait
Using AI Code Generation
1element = driver.find_element(:name, 'q')2element = wait.until { driver.find_element(:name, 'q') }3element = wait.until { driver.find_element(:name, 'q') }4element = wait.until { driver.find_element(:name, 'q') }5element = wait.until { driver.find_element(:name, 'q') }
wait
Using AI Code Generation
1driver.find_element(:name, 'q').send_keys "selenium tutorial"2driver.find_element(:name, 'btnK').click3driver.find_element(:link, 'Selenium Tutorial').click
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!!