Best Capybara code snippet using Capybara.adjust_server_port
session.rb
Source:session.rb  
...246          # and/or single page apps where only the url fragment changes247          visit_uri_parts[:path] = base_uri.path + visit_uri.path248          visit_uri = base_uri.merge(visit_uri_parts)249        end250        adjust_server_port(visit_uri)251      end252      driver.visit(visit_uri.to_s)253    end254    ##255    #256    # Refresh the page.257    #258    def refresh259      raise_server_error!260      driver.refresh261    end262    ##263    #264    # Move back a single entry in the browser's history.265    #266    def go_back267      driver.go_back268    end269    ##270    #271    # Move forward a single entry in the browser's history.272    #273    def go_forward274      driver.go_forward275    end276    ##277    # @!method send_keys278    #   @see Capybara::Node::Element#send_keys279    #280    def send_keys(*args, **kw_args)281      driver.send_keys(*args, **kw_args)282    end283    ##284    #285    # Executes the given block within the context of a node. {#within} takes the286    # same options as {Capybara::Node::Finders#find #find}, as well as a block. For the duration of the287    # block, any command to Capybara will be handled as though it were scoped288    # to the given element.289    #290    #     within(:xpath, './/div[@id="delivery-address"]') do291    #       fill_in('Street', with: '12 Main Street')292    #     end293    #294    # Just as with `#find`, if multiple elements match the selector given to295    # {#within}, an error will be raised, and just as with `#find`, this296    # behaviour can be controlled through the `:match` and `:exact` options.297    #298    # It is possible to omit the first parameter, in that case, the selector is299    # assumed to be of the type set in {Capybara.configure default_selector}.300    #301    #     within('div#delivery-address') do302    #       fill_in('Street', with: '12 Main Street')303    #     end304    #305    # Note that a lot of uses of {#within} can be replaced more succinctly with306    # chaining:307    #308    #     find('div#delivery-address').fill_in('Street', with: '12 Main Street')309    #310    # @overload within(*find_args)311    #   @param (see Capybara::Node::Finders#all)312    #313    # @overload within(a_node)314    #   @param [Capybara::Node::Base] a_node   The node in whose scope the block should be evaluated315    #316    # @raise  [Capybara::ElementNotFound]      If the scope can't be found before time expires317    #318    def within(*args, **kw_args)319      new_scope = args.first.respond_to?(:to_capybara_node) ? args.first.to_capybara_node : find(*args, **kw_args)320      begin321        scopes.push(new_scope)322        yield if block_given?323      ensure324        scopes.pop325      end326    end327    alias_method :within_element, :within328    ##329    #330    # Execute the given block within the a specific fieldset given the id or legend of that fieldset.331    #332    # @param [String] locator    Id or legend of the fieldset333    #334    def within_fieldset(locator, &block)335      within(:fieldset, locator, &block)336    end337    ##338    #339    # Execute the given block within the a specific table given the id or caption of that table.340    #341    # @param [String] locator    Id or caption of the table342    #343    def within_table(locator, &block)344      within(:table, locator, &block)345    end346    ##347    #348    # Switch to the given frame.349    #350    # If you use this method you are responsible for making sure you switch back to the parent frame when done in the frame changed to.351    # {#within_frame} is preferred over this method and should be used when possible.352    # May not be supported by all drivers.353    #354    # @overload switch_to_frame(element)355    #   @param [Capybara::Node::Element] element    iframe/frame element to switch to356    # @overload switch_to_frame(location)357    #   @param [Symbol] location relative location of the frame to switch to358    #                            * :parent - the parent frame359    #                            * :top - the top level document360    #361    def switch_to_frame(frame)362      case frame363      when Capybara::Node::Element364        driver.switch_to_frame(frame)365        scopes.push(:frame)366      when :parent367        if scopes.last != :frame368          raise Capybara::ScopeError, "`switch_to_frame(:parent)` cannot be called from inside a descendant frame's "\369                                      '`within` block.'370        end371        scopes.pop372        driver.switch_to_frame(:parent)373      when :top374        idx = scopes.index(:frame)375        top_level_scopes = [:frame, nil]376        if idx377          if scopes.slice(idx..-1).any? { |scope| !top_level_scopes.include?(scope) }378            raise Capybara::ScopeError, "`switch_to_frame(:top)` cannot be called from inside a descendant frame's "\379                                        '`within` block.'380          end381          scopes.slice!(idx..-1)382          driver.switch_to_frame(:top)383        end384      else385        raise ArgumentError, 'You must provide a frame element, :parent, or :top when calling switch_to_frame'386      end387    end388    ##389    #390    # Execute the given block within the given iframe using given frame, frame name/id or index.391    # May not be supported by all drivers.392    #393    # @overload within_frame(element)394    #   @param [Capybara::Node::Element]  frame element395    # @overload within_frame([kind = :frame], locator, **options)396    #   @param [Symbol] kind      Optional selector type (:frame, :css, :xpath, etc.) - Defaults to :frame397    #   @param [String] locator   The locator for the given selector kind.  For :frame this is the name/id of a frame/iframe element398    # @overload within_frame(index)399    #   @param [Integer] index         index of a frame (0 based)400    def within_frame(*args, **kw_args)401      switch_to_frame(_find_frame(*args, **kw_args))402      begin403        yield if block_given?404      ensure405        switch_to_frame(:parent)406      end407    end408    ##409    # @return [Capybara::Window]   current window410    #411    def current_window412      Window.new(self, driver.current_window_handle)413    end414    ##415    # Get all opened windows.416    # The order of windows in returned array is not defined.417    # The driver may sort windows by their creation time but it's not required.418    #419    # @return [Array<Capybara::Window>]   an array of all windows420    #421    def windows422      driver.window_handles.map do |handle|423        Window.new(self, handle)424      end425    end426    ##427    # Open a new window.428    # The current window doesn't change as the result of this call.429    # It should be switched to explicitly.430    #431    # @return [Capybara::Window]   window that has been opened432    #433    def open_new_window(kind = :tab)434      window_opened_by do435        if driver.method(:open_new_window).arity.zero?436          driver.open_new_window437        else438          driver.open_new_window(kind)439        end440      end441    end442    ##443    # Switch to the given window.444    #445    # @overload switch_to_window(&block)446    #   Switches to the first window for which given block returns a value other than false or nil.447    #   If window that matches block can't be found, the window will be switched back and {Capybara::WindowError} will be raised.448    #   @example449    #     window = switch_to_window { title == 'Page title' }450    #   @raise [Capybara::WindowError]     if no window matches given block451    # @overload switch_to_window(window)452    #   @param window [Capybara::Window]   window that should be switched to453    #   @raise [Capybara::Driver::Base#no_such_window_error] if nonexistent (e.g. closed) window was passed454    #455    # @return [Capybara::Window]         window that has been switched to456    # @raise [Capybara::ScopeError]        if this method is invoked inside {#within} or457    #   {#within_frame} methods458    # @raise [ArgumentError]               if both or neither arguments were provided459    #460    def switch_to_window(window = nil, **options, &window_locator)461      raise ArgumentError, '`switch_to_window` can take either a block or a window, not both' if window && window_locator462      raise ArgumentError, '`switch_to_window`: either window or block should be provided' if !window && !window_locator463      unless scopes.last.nil?464        raise Capybara::ScopeError, '`switch_to_window` is not supposed to be invoked from '\465                                    '`within` or `within_frame` blocks.'466      end467      _switch_to_window(window, **options, &window_locator)468    end469    ##470    # This method does the following:471    #472    # 1. Switches to the given window (it can be located by window instance/lambda/string).473    # 2. Executes the given block (within window located at previous step).474    # 3. Switches back (this step will be invoked even if an exception occurs at the second step).475    #476    # @overload within_window(window) { do_something }477    #   @param window [Capybara::Window]       instance of {Capybara::Window} class478    #     that will be switched to479    #   @raise [driver#no_such_window_error] if nonexistent (e.g. closed) window was passed480    # @overload within_window(proc_or_lambda) { do_something }481    #   @param lambda [Proc]                  First window for which lambda482    #     returns a value other than false or nil will be switched to.483    #   @example484    #     within_window(->{ page.title == 'Page title' }) { click_button 'Submit' }485    #   @raise [Capybara::WindowError]         if no window matching lambda was found486    #487    # @raise [Capybara::ScopeError]        if this method is invoked inside {#within_frame} method488    # @return                              value returned by the block489    #490    def within_window(window_or_proc)491      original = current_window492      scopes << nil493      begin494        case window_or_proc495        when Capybara::Window496          _switch_to_window(window_or_proc) unless original == window_or_proc497        when Proc498          _switch_to_window { window_or_proc.call }499        else500          raise ArgumentError, '`#within_window` requires a `Capybara::Window` instance or a lambda'501        end502        begin503          yield if block_given?504        ensure505          _switch_to_window(original) unless original == window_or_proc506        end507      ensure508        scopes.pop509      end510    end511    ##512    # Get the window that has been opened by the passed block.513    # It will wait for it to be opened (in the same way as other Capybara methods wait).514    # It's better to use this method than `windows.last`515    # {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}.516    #517    # @overload window_opened_by(**options, &block)518    #   @param options [Hash]519    #   @option options [Numeric] :wait  maximum wait time. Defaults to {Capybara.configure default_max_wait_time}520    #   @return [Capybara::Window]       the window that has been opened within a block521    #   @raise [Capybara::WindowError]   if block passed to window hasn't opened window522    #     or opened more than one window523    #524    def window_opened_by(**options)525      old_handles = driver.window_handles526      yield527      synchronize_windows(options) do528        opened_handles = (driver.window_handles - old_handles)529        if opened_handles.size != 1530          raise Capybara::WindowError, 'block passed to #window_opened_by '\531                                       "opened #{opened_handles.size} windows instead of 1"532        end533        Window.new(self, opened_handles.first)534      end535    end536    ##537    #538    # Execute the given script, not returning a result. This is useful for scripts that return539    # complex objects, such as jQuery statements. {#execute_script} should be used over540    # {#evaluate_script} whenever possible.541    #542    # @param [String] script   A string of JavaScript to execute543    # @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 drivers544    #545    def execute_script(script, *args)546      @touched = true547      driver.execute_script(script, *driver_args(args))548    end549    ##550    #551    # Evaluate the given JavaScript and return the result. Be careful when using this with552    # scripts that return complex objects, such as jQuery statements. {#execute_script} might553    # be a better alternative.554    #555    # @param  [String] script   A string of JavaScript to evaluate556    # @param           args     Optional arguments that will be passed to the script557    # @return [Object]          The result of the evaluated JavaScript (may be driver specific)558    #559    def evaluate_script(script, *args)560      @touched = true561      result = driver.evaluate_script(script.strip, *driver_args(args))562      element_script_result(result)563    end564    ##565    #566    # Evaluate the given JavaScript and obtain the result from a callback function which will be passed as the last argument to the script.567    #568    # @param  [String] script   A string of JavaScript to evaluate569    # @param           args     Optional arguments that will be passed to the script570    # @return [Object]          The result of the evaluated JavaScript (may be driver specific)571    #572    def evaluate_async_script(script, *args)573      @touched = true574      result = driver.evaluate_async_script(script, *driver_args(args))575      element_script_result(result)576    end577    ##578    #579    # Execute the block, accepting a alert.580    #581    # @!macro modal_params582    #   Expects a block whose actions will trigger the display modal to appear.583    #   @example584    #     $0 do585    #       click_link('link that triggers appearance of system modal')586    #     end587    #   @overload $0(text, **options, &blk)588    #     @param text [String, Regexp]  Text or regex to match against the text in the modal. If not provided any modal is matched.589    #     @option options [Numeric] :wait  Maximum time to wait for the modal to appear after executing the block. Defaults to {Capybara.configure default_max_wait_time}.590    #     @yield Block whose actions will trigger the system modal591    #   @overload $0(**options, &blk)592    #     @option options [Numeric] :wait  Maximum time to wait for the modal to appear after executing the block. Defaults to {Capybara.configure default_max_wait_time}.593    #     @yield Block whose actions will trigger the system modal594    #   @return [String]  the message shown in the modal595    #   @raise [Capybara::ModalNotFound]  if modal dialog hasn't been found596    #597    def accept_alert(text = nil, **options, &blk)598      accept_modal(:alert, text, options, &blk)599    end600    ##601    #602    # Execute the block, accepting a confirm.603    #604    # @macro modal_params605    #606    def accept_confirm(text = nil, **options, &blk)607      accept_modal(:confirm, text, options, &blk)608    end609    ##610    #611    # Execute the block, dismissing a confirm.612    #613    # @macro modal_params614    #615    def dismiss_confirm(text = nil, **options, &blk)616      dismiss_modal(:confirm, text, options, &blk)617    end618    ##619    #620    # Execute the block, accepting a prompt, optionally responding to the prompt.621    #622    # @macro modal_params623    # @option options [String] :with   Response to provide to the prompt624    #625    def accept_prompt(text = nil, **options, &blk)626      accept_modal(:prompt, text, options, &blk)627    end628    ##629    #630    # Execute the block, dismissing a prompt.631    #632    # @macro modal_params633    #634    def dismiss_prompt(text = nil, **options, &blk)635      dismiss_modal(:prompt, text, options, &blk)636    end637    ##638    #639    # Save a snapshot of the page. If {Capybara.configure asset_host} is set it will inject `base` tag640    # pointing to {Capybara.configure asset_host}.641    #642    # If invoked without arguments it will save file to {Capybara.configure save_path}643    # and file will be given randomly generated filename. If invoked with a relative path644    # the path will be relative to {Capybara.configure save_path}.645    #646    # @param [String] path  the path to where it should be saved647    # @return [String]      the path to which the file was saved648    #649    def save_page(path = nil)650      prepare_path(path, 'html').tap do |p_path|651        File.write(p_path, Capybara::Helpers.inject_asset_host(body, host: config.asset_host), mode: 'wb')652      end653    end654    ##655    #656    # Save a snapshot of the page and open it in a browser for inspection.657    #658    # If invoked without arguments it will save file to {Capybara.configure save_path}659    # and file will be given randomly generated filename. If invoked with a relative path660    # the path will be relative to {Capybara.configure save_path}.661    #662    # @param [String] path  the path to where it should be saved663    #664    def save_and_open_page(path = nil)665      save_page(path).tap { |s_path| open_file(s_path) }666    end667    ##668    #669    # Save a screenshot of page.670    #671    # If invoked without arguments it will save file to {Capybara.configure save_path}672    # and file will be given randomly generated filename. If invoked with a relative path673    # the path will be relative to {Capybara.configure save_path}.674    #675    # @param [String] path    the path to where it should be saved676    # @param [Hash] options   a customizable set of options677    # @return [String]        the path to which the file was saved678    def save_screenshot(path = nil, **options)679      prepare_path(path, 'png').tap { |p_path| driver.save_screenshot(p_path, **options) }680    end681    ##682    #683    # Save a screenshot of the page and open it for inspection.684    #685    # If invoked without arguments it will save file to {Capybara.configure save_path}686    # and file will be given randomly generated filename. If invoked with a relative path687    # the path will be relative to {Capybara.configure save_path}.688    #689    # @param [String] path    the path to where it should be saved690    # @param [Hash] options   a customizable set of options691    #692    def save_and_open_screenshot(path = nil, **options)693      save_screenshot(path, **options).tap { |s_path| open_file(s_path) }694    end695    def document696      @document ||= Capybara::Node::Document.new(self, driver)697    end698    NODE_METHODS.each do |method|699      if RUBY_VERSION >= '2.7'700        class_eval <<~METHOD, __FILE__, __LINE__ + 1701          def #{method}(...)702            @touched = true703            current_scope.#{method}(...)704          end705        METHOD706      else707        define_method method do |*args, &block|708          @touched = true709          current_scope.send(method, *args, &block)710        end711      end712    end713    DOCUMENT_METHODS.each do |method|714      if RUBY_VERSION >= '2.7'715        class_eval <<~METHOD, __FILE__, __LINE__ + 1716          def #{method}(...)717            document.#{method}(...)718          end719        METHOD720      else721        define_method method do |*args, &block|722          document.send(method, *args, &block)723        end724      end725    end726    def inspect727      %(#<Capybara::Session>)728    end729    def current_scope730      scope = scopes.last731      [nil, :frame].include?(scope) ? document : scope732    end733    ##734    #735    # Yield a block using a specific maximum wait time.736    #737    def using_wait_time(seconds, &block)738      if Capybara.threadsafe739        begin740          previous_wait_time = config.default_max_wait_time741          config.default_max_wait_time = seconds742          yield743        ensure744          config.default_max_wait_time = previous_wait_time745        end746      else747        Capybara.using_wait_time(seconds, &block)748      end749    end750    ##751    #752    # Accepts a block to set the configuration options if {Capybara.configure threadsafe} is `true`. Note that some options only have an effect753    # if set at initialization time, so look at the configuration block that can be passed to the initializer too.754    #755    def configure756      raise 'Session configuration is only supported when Capybara.threadsafe == true' unless Capybara.threadsafe757      yield config758    end759    def self.instance_created?760      @@instance_created761    end762    def config763      @config ||= if Capybara.threadsafe764        Capybara.session_options.dup765      else766        Capybara::ReadOnlySessionConfig.new(Capybara.session_options)767      end768    end769    def server_url770      @server&.base_url771    end772  private773    @@instance_created = false # rubocop:disable Style/ClassVars774    def driver_args(args)775      args.map { |arg| arg.is_a?(Capybara::Node::Element) ? arg.base : arg }776    end777    def accept_modal(type, text_or_options, options, &blk)778      driver.accept_modal(type, **modal_options(text_or_options, **options), &blk)779    end780    def dismiss_modal(type, text_or_options, options, &blk)781      driver.dismiss_modal(type, **modal_options(text_or_options, **options), &blk)782    end783    def modal_options(text = nil, **options)784      options[:text] ||= text unless text.nil?785      options[:wait] ||= config.default_max_wait_time786      options787    end788    def open_file(path)789      require 'launchy'790      Launchy.open(path)791    rescue LoadError792      warn "File saved to #{path}.\nPlease install the launchy gem to open the file automatically."793    end794    def prepare_path(path, extension)795      File.expand_path(path || default_fn(extension), config.save_path).tap do |p_path|796        FileUtils.mkdir_p(File.dirname(p_path))797      end798    end799    def default_fn(extension)800      timestamp = Time.new.strftime('%Y%m%d%H%M%S')801      "capybara-#{timestamp}#{rand(10**10)}.#{extension}"802    end803    def scopes804      @scopes ||= [nil]805    end806    def element_script_result(arg)807      case arg808      when Array809        arg.map { |subarg| element_script_result(subarg) }810      when Hash811        arg.transform_values! { |value| element_script_result(value) }812      when Capybara::Driver::Node813        Capybara::Node::Element.new(self, arg, nil, nil)814      else815        arg816      end817    end818    def adjust_server_port(uri)819      uri.port ||= @server.port if @server && config.always_include_port820    end821    def _find_frame(*args, **kw_args)822      case args[0]823      when Capybara::Node::Element824        args[0]825      when String, nil826        find(:frame, *args, **kw_args)827      when Symbol828        find(*args, **kw_args)829      when Integer830        idx = args[0]831        all(:frame, minimum: idx + 1)[idx]832      else...adjust_server_port
Using AI Code Generation
1  Capybara::Selenium::Driver.new(app, :browser => :chrome)2  Capybara::Selenium::Driver.new(app, :browser => :chrome)3  Capybara::Selenium::Driver.new(app, :browser => :chrome)4  Capybara::Selenium::Driver.new(app, :browser => :chrome)adjust_server_port
Using AI Code Generation
1World(Capybara)2  Capybara::Poltergeist::Driver.new(app, js_errors: false)3  Capybara::Poltergeist::Driver.new(app, inspector: true, js_errors: false)4  Capybara::Selenium::Driver.new(app, browser: :chrome)5  Capybara::Selenium::Driver.new(app, browser: :firefox)6  Capybara::Selenium::Driver.new(app, browser: :safari)7  Capybara::Selenium::Driver.new(app, browser: :internet_explorer)8  Capybara::Poltergeist::Driver.new(app, js_errors: false)9  Capybara::Poltergeist::Driver.new(app, inspector: true, js_errors: false)10  Capybara::Selenium::Driver.new(app, browser: :chrome)11  Capybara::Selenium::Driver.new(app, browser: :firefox)adjust_server_port
Using AI Code Generation
1Capybara.adjust_server_port(8888)2    page.should have_content("some text")3RSpec::Core::Runner.run(["1.rb"])4Capybara.adjust_server_port(8888)5    session = Capybara::Session.new(:webkit)adjust_server_port
Using AI Code Generation
1Capybara.adjust_server_port(3000)2Capybara.adjust_server_port(3000)3Capybara.adjust_server_port(3000)4Capybara.adjust_server_port(3000)5Capybara.adjust_server_port(3000)6Capybara.adjust_server_port(3000)7Capybara.adjust_server_port(3000)8Capybara.adjust_server_port(3000)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!!
