How to use _switch_to_window method of Capybara Package

Best Capybara code snippet using Capybara._switch_to_window

session.rb

Source:session.rb Github

copy

Full Screen

...466 elsif !scopes.last.nil?467 raise Capybara::ScopeError, "`switch_to_window` is not supposed to be invoked from "\468 "`within` or `within_frame` blocks."469 end470 _switch_to_window(window, options, &window_locator)471 end472 ##473 # This method does the following:474 #475 # 1. Switches to the given window (it can be located by window instance/lambda/string).476 # 2. Executes the given block (within window located at previous step).477 # 3. Switches back (this step will be invoked even if exception will happen at second step)478 #479 # @overload within_window(window) { do_something }480 # @param window [Capybara::Window] instance of `Capybara::Window` class481 # that will be switched to482 # @raise [driver#no_such_window_error] if nonexistent (e.g. closed) window was passed483 # @overload within_window(proc_or_lambda) { do_something }484 # @param lambda [Proc] lambda. First window for which lambda485 # returns a value other than false or nil will be switched to.486 # @example487 # within_window(->{ page.title == 'Page title' }) { click_button 'Submit' }488 # @raise [Capybara::WindowError] if no window matching lambda was found489 # @overload within_window(string) { do_something }490 # @deprecated Pass window or lambda instead491 # @param [String] handle, name, url or title of the window492 #493 # @raise [Capybara::ScopeError] if this method is invoked inside `within_frame` method494 # @return value returned by the block495 #496 def within_window(window_or_handle)497 if window_or_handle.instance_of?(Capybara::Window)498 original = current_window499 scopes << nil500 begin501 _switch_to_window(window_or_handle) unless original == window_or_handle502 begin503 yield504 ensure505 _switch_to_window(original) unless original == window_or_handle506 end507 ensure508 scopes.pop509 end510 elsif window_or_handle.is_a?(Proc)511 original = current_window512 scopes << nil513 begin514 _switch_to_window { window_or_handle.call }515 begin516 yield517 ensure518 _switch_to_window(original)519 end520 ensure521 scopes.pop522 end523 else524 offending_line = caller.first525 file_line = offending_line.match(/^(.+?):(\d+)/)[0]526 warn "DEPRECATION WARNING: Passing string argument to #within_window is deprecated. "\527 "Pass window object or lambda. (called from #{file_line})"528 begin529 scopes << nil530 driver.within_window(window_or_handle) { yield }531 ensure532 scopes.pop533 end534 end535 end536 ##537 # Get the window that has been opened by the passed block.538 # It will wait for it to be opened (in the same way as other Capybara methods wait).539 # It's better to use this method than `windows.last`540 # {https://dvcs.w3.org/hg/webdriver/raw-file/default/webdriver-spec.html#h_note_10 as order of windows isn't defined in some drivers}541 #542 # @param options [Hash]543 # @option options [Numeric] :wait (Capybara.default_max_wait_time) maximum wait time544 # @return [Capybara::Window] the window that has been opened within a block545 # @raise [Capybara::WindowError] if block passed to window hasn't opened window546 # or opened more than one window547 #548 def window_opened_by(options = {}, &block)549 old_handles = driver.window_handles550 block.call551 wait_time = Capybara::Queries::BaseQuery.wait(options, config.default_max_wait_time)552 document.synchronize(wait_time, errors: [Capybara::WindowError]) do553 opened_handles = (driver.window_handles - old_handles)554 if opened_handles.size != 1555 raise Capybara::WindowError, "block passed to #window_opened_by "\556 "opened #{opened_handles.size} windows instead of 1"557 end558 Window.new(self, opened_handles.first)559 end560 end561 ##562 #563 # Execute the given script, not returning a result. This is useful for scripts that return564 # complex objects, such as jQuery statements. +execute_script+ should be used over565 # +evaluate_script+ whenever possible.566 #567 # @param [String] script A string of JavaScript to execute568 # @param args Optional arguments that will be passed to the script. Driver support for this is optional and types of objects supported may differ between drivers569 #570 def execute_script(script, *args)571 @touched = true572 if args.empty?573 driver.execute_script(script)574 else575 raise Capybara::NotSupportedByDriverError, "The current driver does not support execute_script arguments" if driver.method(:execute_script).arity == 1576 driver.execute_script(script, *args.map { |arg| arg.is_a?(Capybara::Node::Element) ? arg.base : arg} )577 end578 end579 ##580 #581 # Evaluate the given JavaScript and return the result. Be careful when using this with582 # scripts that return complex objects, such as jQuery statements. +execute_script+ might583 # be a better alternative.584 #585 # @param [String] script A string of JavaScript to evaluate586 # @return [Object] The result of the evaluated JavaScript (may be driver specific)587 #588 def evaluate_script(script, *args)589 @touched = true590 result = if args.empty?591 driver.evaluate_script(script)592 else593 raise Capybara::NotSupportedByDriverError, "The current driver does not support evaluate_script arguments" if driver.method(:evaluate_script).arity == 1594 driver.evaluate_script(script, *args.map { |arg| arg.is_a?(Capybara::Node::Element) ? arg.base : arg} )595 end596 element_script_result(result)597 end598 ##599 #600 # Evaluate the given JavaScript and obtain the result from a callback function which will be passed as the last argument to the script.601 #602 # @param [String] script A string of JavaScript to evaluate603 # @return [Object] The result of the evaluated JavaScript (may be driver specific)604 #605 def evaluate_async_script(script, *args)606 @touched = true607 result = if args.empty?608 driver.evaluate_async_script(script)609 else610 raise Capybara::NotSupportedByDriverError, "The current driver does not support evaluate_async_script arguments" if driver.method(:evaluate_async_script).arity == 1611 driver.evaluate_async_script(script, *args.map { |arg| arg.is_a?(Capybara::Node::Element) ? arg.base : arg} )612 end613 element_script_result(result)614 end615 ##616 #617 # Execute the block, accepting a alert.618 #619 # @!macro modal_params620 # Expects a block whose actions will trigger the display modal to appear621 # @example622 # $0 do623 # click_link('link that triggers appearance of system modal')624 # end625 # @overload $0(text, options = {}, &blk)626 # @param text [String, Regexp] Text or regex to match against the text in the modal. If not provided any modal is matched627 # @option options [Numeric] :wait (Capybara.default_max_wait_time) Maximum time to wait for the modal to appear after executing the block.628 # @yield Block whose actions will trigger the system modal629 # @overload $0(options = {}, &blk)630 # @option options [Numeric] :wait (Capybara.default_max_wait_time) Maximum time to wait for the modal to appear after executing the block.631 # @yield Block whose actions will trigger the system modal632 # @return [String] the message shown in the modal633 # @raise [Capybara::ModalNotFound] if modal dialog hasn't been found634 #635 #636 def accept_alert(text_or_options=nil, options={}, &blk)637 accept_modal(:alert, text_or_options, options, &blk)638 end639 ##640 #641 # Execute the block, accepting a confirm.642 #643 # @macro modal_params644 #645 def accept_confirm(text_or_options=nil, options={}, &blk)646 accept_modal(:confirm, text_or_options, options, &blk)647 end648 ##649 #650 # Execute the block, dismissing a confirm.651 #652 # @macro modal_params653 #654 def dismiss_confirm(text_or_options=nil, options={}, &blk)655 dismiss_modal(:confirm, text_or_options, options, &blk)656 end657 ##658 #659 # Execute the block, accepting a prompt, optionally responding to the prompt.660 #661 # @macro modal_params662 # @option options [String] :with Response to provide to the prompt663 #664 def accept_prompt(text_or_options=nil, options={}, &blk)665 accept_modal(:prompt, text_or_options, options, &blk)666 end667 ##668 #669 # Execute the block, dismissing a prompt.670 #671 # @macro modal_params672 #673 def dismiss_prompt(text_or_options=nil, options={}, &blk)674 dismiss_modal(:prompt, text_or_options, options, &blk)675 end676 ##677 #678 # Save a snapshot of the page. If `Capybara.asset_host` is set it will inject `base` tag679 # pointing to `asset_host`.680 #681 # If invoked without arguments it will save file to `Capybara.save_path`682 # and file will be given randomly generated filename. If invoked with a relative path683 # the path will be relative to `Capybara.save_path`, which is different from684 # the previous behavior with `Capybara.save_and_open_page_path` where the relative path was685 # relative to Dir.pwd686 #687 # @param [String] path the path to where it should be saved688 # @return [String] the path to which the file was saved689 #690 def save_page(path = nil)691 path = prepare_path(path, 'html')692 File.write(path, Capybara::Helpers.inject_asset_host(body, config.asset_host), mode: 'wb')693 path694 end695 ##696 #697 # Save a snapshot of the page and open it in a browser for inspection.698 #699 # If invoked without arguments it will save file to `Capybara.save_path`700 # and file will be given randomly generated filename. If invoked with a relative path701 # the path will be relative to `Capybara.save_path`, which is different from702 # the previous behavior with `Capybara.save_and_open_page_path` where the relative path was703 # relative to Dir.pwd704 #705 # @param [String] path the path to where it should be saved706 #707 def save_and_open_page(path = nil)708 path = save_page(path)709 open_file(path)710 end711 ##712 #713 # Save a screenshot of page.714 #715 # If invoked without arguments it will save file to `Capybara.save_path`716 # and file will be given randomly generated filename. If invoked with a relative path717 # the path will be relative to `Capybara.save_path`, which is different from718 # the previous behavior with `Capybara.save_and_open_page_path` where the relative path was719 # relative to Dir.pwd720 #721 # @param [String] path the path to where it should be saved722 # @param [Hash] options a customizable set of options723 # @return [String] the path to which the file was saved724 def save_screenshot(path = nil, options = {})725 path = prepare_path(path, 'png')726 driver.save_screenshot(path, options)727 path728 end729 ##730 #731 # Save a screenshot of the page and open it for inspection.732 #733 # If invoked without arguments it will save file to `Capybara.save_path`734 # and file will be given randomly generated filename. If invoked with a relative path735 # the path will be relative to `Capybara.save_path`, which is different from736 # the previous behavior with `Capybara.save_and_open_page_path` where the relative path was737 # relative to Dir.pwd738 #739 # @param [String] path the path to where it should be saved740 # @param [Hash] options a customizable set of options741 #742 def save_and_open_screenshot(path = nil, options = {})743 path = save_screenshot(path, options)744 open_file(path)745 end746 def document747 @document ||= Capybara::Node::Document.new(self, driver)748 end749 NODE_METHODS.each do |method|750 define_method method do |*args, &block|751 @touched = true752 current_scope.send(method, *args, &block)753 end754 end755 DOCUMENT_METHODS.each do |method|756 define_method method do |*args, &block|757 document.send(method, *args, &block)758 end759 end760 def inspect761 %(#<Capybara::Session>)762 end763 def current_scope764 scope = scopes.last765 scope = document if [nil, :frame].include? scope766 scope767 end768 ##769 #770 # Yield a block using a specific wait time771 #772 def using_wait_time(seconds)773 if Capybara.threadsafe774 begin775 previous_wait_time = config.default_max_wait_time776 config.default_max_wait_time = seconds777 yield778 ensure779 config.default_max_wait_time = previous_wait_time780 end781 else782 Capybara.using_wait_time(seconds) { yield }783 end784 end785 ##786 #787 # Accepts a block to set the configuration options if Capybara.threadsafe == true. Note that some options only have an effect788 # if set at initialization time, so look at the configuration block that can be passed to the initializer too789 #790 def configure791 raise "Session configuration is only supported when Capybara.threadsafe == true" unless Capybara.threadsafe792 yield config793 end794 def self.instance_created?795 @@instance_created796 end797 def config798 @config ||= if Capybara.threadsafe799 Capybara.session_options.dup800 else801 Capybara::ReadOnlySessionConfig.new(Capybara.session_options)802 end803 end804 private805 @@instance_created = false806 def accept_modal(type, text_or_options, options, &blk)807 driver.accept_modal(type, modal_options(text_or_options, options), &blk)808 end809 def dismiss_modal(type, text_or_options, options, &blk)810 driver.dismiss_modal(type, modal_options(text_or_options, options), &blk)811 end812 def modal_options(text_or_options, options)813 text_or_options, options = nil, text_or_options if text_or_options.is_a?(Hash)814 options[:text] ||= text_or_options unless text_or_options.nil?815 options[:wait] ||= config.default_max_wait_time816 options817 end818 def open_file(path)819 begin820 require "launchy"821 Launchy.open(path)822 rescue LoadError823 warn "File saved to #{path}."824 warn "Please install the launchy gem to open the file automatically."825 end826 end827 def prepare_path(path, extension)828 if config.save_path || config.save_and_open_page_path.nil?829 path = File.expand_path(path || default_fn(extension), config.save_path)830 else831 path = File.expand_path(default_fn(extension), config.save_and_open_page_path) if path.nil?832 end833 FileUtils.mkdir_p(File.dirname(path))834 path835 end836 def default_fn(extension)837 timestamp = Time.new.strftime("%Y%m%d%H%M%S")838 "capybara-#{timestamp}#{rand(10**10)}.#{extension}"839 end840 def scopes841 @scopes ||= [nil]842 end843 def element_script_result(arg)844 case arg845 when Array846 arg.map { |e| element_script_result(e) }847 when Hash848 arg.each { |k, v| arg[k] = element_script_result(v) }849 when Capybara::Driver::Node850 Capybara::Node::Element.new(self, arg, nil, nil)851 else852 arg853 end854 end855 def _find_frame(*args)856 within(document) do # Previous 2.x versions ignored current scope when finding frames - consider changing in 3.0857 case args[0]858 when Capybara::Node::Element859 args[0]860 when String, Hash861 find(:frame, *args)862 when Symbol863 find(*args)864 when Integer865 idx = args[0]866 all(:frame, minimum: idx+1)[idx]867 else868 raise TypeError869 end870 end871 end872 def _switch_to_window(window = nil, options= {})873 options, window = window, nil if window.is_a? Hash874 raise Capybara::ScopeError, "Window cannot be switched inside a `within_frame` block" if scopes.include?(:frame)875 raise Capybara::ScopeError, "Window cannot be switch inside a `within` block" unless scopes.last.nil?876 if window877 driver.switch_to_window(window.handle)878 window879 else880 wait_time = Capybara::Queries::BaseQuery.wait(options, config.default_max_wait_time)881 document.synchronize(wait_time, errors: [Capybara::WindowError]) do882 original_window_handle = driver.current_window_handle883 begin884 driver.window_handles.each do |handle|885 driver.switch_to_window handle886 if yield...

Full Screen

Full Screen

_switch_to_window

Using AI Code Generation

copy

Full Screen

1visit('/')2page.driver.browser.switch_to.window(page.driver.browser.window_handles.first)3page.save_screenshot("1.png")

Full Screen

Full Screen

_switch_to_window

Using AI Code Generation

copy

Full Screen

1 Capybara::Poltergeist::Driver.new(app, js_errors: false, timeout: 60, phantomjs_options: ['--load-images=no', '--disk-cache=false'], debug: false)2Capybara::Session.new(:poltergeist).visit("/")3Capybara::Session.new(:poltergeist).switch_to_window(Capybara::Session.new(:poltergeist).window_handles.last)4Capybara::Session.new(:poltergeist).visit("https://www.google.com")5Capybara::Session.new(:poltergeist).switch_to_window(Capybara::Session.new(:poltergeist).window_handles.first)6Capybara::Session.new(:poltergeist).visit("https://www.google.com")7Capybara::Session.new(:poltergeist).switch_to_window(Capybara::Session.new(:poltergeist).window_handles.last)8Capybara::Session.new(:poltergeist).visit("https://www.google.com")9Capybara::Session.new(:poltergeist).switch_to_window(Capybara::Session.new(:poltergeist).window_handles.first)10Capybara::Session.new(:poltergeist).visit("https://www.google.com")11Capybara::Session.new(:poltergeist).switch_to_window(Capybara::Session.new(:poltergeist).window_handles.last)12Capybara::Session.new(:poltergeist).visit("https://www.google.com")13Capybara::Session.new(:poltergeist).switch_to_window(Capybara::Session.new(:poltergeist).window_handles.first)14Capybara::Session.new(:poltergeist).visit("https://www.google.com")15Capybara::Session.new(:poltergeist).switch_to_window(Capybara::Session.new(:poltergeist).window_handles.last)16Capybara::Session.new(:poltergeist).visit("https://www.google.com")

Full Screen

Full Screen

_switch_to_window

Using AI Code Generation

copy

Full Screen

1click_link 'Ruby (programming language) - Wikipedia, the free ...'2Capybara.current_session.driver.browser.switch_to_window(Capybara.current_session.driver.browser.window_handles.last)3Capybara.current_session.driver.browser.switch_to_window(Capybara.current_session.driver.browser.window_handles.first)4click_link 'Ruby (programming language) - Wikipedia, the free ...'5page.driver.browser.switch_to_window(page.driver.browser.window_handles.last)6page.driver.browser.switch_to_window(page.driver.browser.window_handles.first)

Full Screen

Full Screen

_switch_to_window

Using AI Code Generation

copy

Full Screen

1page.find(:css, "a[href='http://www.google.co.in/imghp?hl=en&tab=wi']").click2_switch_to_window("Google Images")3_switch_to_window("Google")

Full Screen

Full Screen

_switch_to_window

Using AI Code Generation

copy

Full Screen

1 config.allow_url("http://www.google.com")2 def _switch_to_window(window_name)3 driver.switch_to_window(window_name)4Capybara.visit("/")5Capybara.click_link("Gmail")6Capybara._switch_to_window("Gmail")7Capybara.click_link("Sign in")8Capybara.fill_in("Email", :with => "

Full Screen

Full Screen

_switch_to_window

Using AI Code Generation

copy

Full Screen

1_switch_to_window(1)2_close_window(1)3_switch_to_window(1)4_close_window(1)5_switch_to_window(1)6_close_window(1)7_switch_to_window(1)8_close_window(1)

Full Screen

Full Screen

Automation Testing Tutorials

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.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run Capybara automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Most used method in

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful