How to use path method of Capybara.Driver Package

Best Capybara code snippet using Capybara.Driver.path

session.rb

Source:session.rb Github

copy

Full Screen

...23 # config.app_host = "http://my_host.dev"24 # end25 #26 # Session provides a number of methods for controlling the navigation of the page, such as +visit+,27 # +current_path, and so on. It also delegate a number of methods to a Capybara::Document, representing28 # the current HTML document. This allows interaction:29 #30 # session.fill_in('q', with: 'Capybara')31 # session.click_button('Search')32 # expect(session).to have_content('Capybara')33 #34 # When using capybara/dsl, the Session is initialized automatically for you.35 #36 class Session37 include Capybara::SessionMatchers38 NODE_METHODS = [39 :all, :first, :attach_file, :text, :check, :choose,40 :click_link_or_button, :click_button, :click_link, :field_labeled,41 :fill_in, :find, :find_all, :find_button, :find_by_id, :find_field, :find_link,42 :has_content?, :has_text?, :has_css?, :has_no_content?, :has_no_text?,43 :has_no_css?, :has_no_xpath?, :resolve, :has_xpath?, :select, :uncheck,44 :has_link?, :has_no_link?, :has_button?, :has_no_button?, :has_field?,45 :has_no_field?, :has_checked_field?, :has_unchecked_field?,46 :has_no_table?, :has_table?, :unselect, :has_select?, :has_no_select?,47 :has_selector?, :has_no_selector?, :click_on, :has_no_checked_field?,48 :has_no_unchecked_field?, :query, :assert_selector, :assert_no_selector,49 :assert_all_of_selectors, :assert_none_of_selectors,50 :refute_selector, :assert_text, :assert_no_text51 ]52 # @api private53 DOCUMENT_METHODS = [54 :title, :assert_title, :assert_no_title, :has_title?, :has_no_title?55 ]56 SESSION_METHODS = [57 :body, :html, :source, :current_url, :current_host, :current_path,58 :execute_script, :evaluate_script, :visit, :refresh, :go_back, :go_forward,59 :within, :within_element, :within_fieldset, :within_table, :within_frame, :switch_to_frame,60 :current_window, :windows, :open_new_window, :switch_to_window, :within_window, :window_opened_by,61 :save_page, :save_and_open_page, :save_screenshot,62 :save_and_open_screenshot, :reset_session!, :response_headers,63 :status_code, :current_scope,64 :assert_current_path, :assert_no_current_path, :has_current_path?, :has_no_current_path?65 ] + DOCUMENT_METHODS66 MODAL_METHODS = [67 :accept_alert, :accept_confirm, :dismiss_confirm, :accept_prompt,68 :dismiss_prompt69 ]70 DSL_METHODS = NODE_METHODS + SESSION_METHODS + MODAL_METHODS71 attr_reader :mode, :app, :server72 attr_accessor :synchronized73 def initialize(mode, app=nil)74 raise TypeError, "The second parameter to Session::new should be a rack app if passed." if app && !app.respond_to?(:call)75 @@instance_created = true76 @mode = mode77 @app = app78 if block_given?79 raise "A configuration block is only accepted when Capybara.threadsafe == true" unless Capybara.threadsafe80 yield config if block_given?81 end82 if config.run_server and @app and driver.needs_server?83 @server = Capybara::Server.new(@app, config.server_port, config.server_host, config.server_errors).boot84 else85 @server = nil86 end87 @touched = false88 end89 def driver90 @driver ||= begin91 unless Capybara.drivers.has_key?(mode)92 other_drivers = Capybara.drivers.keys.map { |key| key.inspect }93 raise Capybara::DriverNotFoundError, "no driver called #{mode.inspect} was found, available drivers: #{other_drivers.join(', ')}"94 end95 driver = Capybara.drivers[mode].call(app)96 driver.session = self if driver.respond_to?(:session=)97 driver98 end99 end100 ##101 #102 # Reset the session (i.e. remove cookies and navigate to blank page)103 #104 # This method does not:105 #106 # * accept modal dialogs if they are present (Selenium driver now does, others may not)107 # * clear browser cache/HTML 5 local storage/IndexedDB/Web SQL database/etc.108 # * modify state of the driver/underlying browser in any other way109 #110 # as doing so will result in performance downsides and it's not needed to do everything from the list above for most apps.111 #112 # If you want to do anything from the list above on a general basis you can:113 #114 # * write RSpec/Cucumber/etc. after hook115 # * monkeypatch this method116 # * use Ruby's `prepend` method117 #118 def reset!119 if @touched120 driver.reset!121 @touched = false122 end123 @server.wait_for_pending_requests if @server124 raise_server_error!125 end126 alias_method :cleanup!, :reset!127 alias_method :reset_session!, :reset!128 ##129 #130 # Raise errors encountered in the server131 #132 def raise_server_error!133 if @server and @server.error134 # Force an explanation for the error being raised as the exception cause135 begin136 if config.raise_server_errors137 raise CapybaraError, "Your application server raised an error - It has been raised in your test code because Capybara.raise_server_errors == true"138 end139 rescue CapybaraError140 #needed to get the cause set correctly in JRuby -- otherwise we could just do raise @server.error141 raise @server.error, @server.error.message, @server.error.backtrace142 ensure143 @server.reset_error!144 end145 end146 end147 ##148 #149 # Returns a hash of response headers. Not supported by all drivers (e.g. Selenium)150 #151 # @return [Hash{String => String}] A hash of response headers.152 #153 def response_headers154 driver.response_headers155 end156 ##157 #158 # Returns the current HTTP status code as an Integer. Not supported by all drivers (e.g. Selenium)159 #160 # @return [Integer] Current HTTP status code161 #162 def status_code163 driver.status_code164 end165 ##166 #167 # @return [String] A snapshot of the DOM of the current document, as it looks right now (potentially modified by JavaScript).168 #169 def html170 driver.html171 end172 alias_method :body, :html173 alias_method :source, :html174 ##175 #176 # @return [String] Path of the current page, without any domain information177 #178 def current_path179 # Addressable parsing is more lenient than URI180 uri = ::Addressable::URI.parse(current_url)181 # If current_url ends up being nil, won't be able to call .path on a NilClass.182 return nil if uri.nil?183 # Addressable doesn't support opaque URIs - we want nil here184 return nil if uri.scheme == "about"185 path = uri.path186 path if path and not path.empty?187 end188 ##189 #190 # @return [String] Host of the current page191 #192 def current_host193 uri = URI.parse(current_url)194 "#{uri.scheme}://#{uri.host}" if uri.host195 end196 ##197 #198 # @return [String] Fully qualified URL of the current page199 #200 def current_url201 driver.current_url202 end203 ##204 #205 # Navigate to the given URL. The URL can either be a relative URL or an absolute URL206 # The behaviour of either depends on the driver.207 #208 # session.visit('/foo')209 # session.visit('http://google.com')210 #211 # For drivers which can run against an external application, such as the selenium driver212 # giving an absolute URL will navigate to that page. This allows testing applications213 # running on remote servers. For these drivers, setting {Capybara.app_host} will make the214 # remote server the default. For example:215 #216 # Capybara.app_host = 'http://google.com'217 # session.visit('/') # visits the google homepage218 #219 # If {Capybara.always_include_port} is set to true and this session is running against220 # a rack application, then the port that the rack application is running on will automatically221 # be inserted into the URL. Supposing the app is running on port `4567`, doing something like:222 #223 # visit("http://google.com/test")224 #225 # Will actually navigate to `http://google.com:4567/test`.226 #227 # @param [#to_s] visit_uri The URL to navigate to. The parameter will be cast to a String.228 #229 def visit(visit_uri)230 raise_server_error!231 @touched = true232 visit_uri = ::Addressable::URI.parse(visit_uri.to_s)233 uri_base = if @server234 ::Addressable::URI.parse(config.app_host || "http://#{@server.host}:#{@server.port}")235 else236 config.app_host && ::Addressable::URI.parse(config.app_host)237 end238 if uri_base && [nil, 'http', 'https'].include?(visit_uri.scheme)239 if visit_uri.relative?240 uri_base.port ||= @server.port if @server && config.always_include_port241 visit_uri_parts = visit_uri.to_hash.delete_if { |k,v| v.nil? }242 # Useful to people deploying to a subdirectory243 # and/or single page apps where only the url fragment changes244 visit_uri_parts[:path] = uri_base.path + visit_uri.path245 visit_uri = uri_base.merge(visit_uri_parts)246 else247 visit_uri.port ||= @server.port if @server && config.always_include_port248 end249 end250 driver.visit(visit_uri.to_s)251 end252 ##253 #254 # Refresh the page255 #256 def refresh257 raise_server_error!258 driver.refresh259 end260 ##261 #262 # Move back a single entry in the browser's history.263 #264 def go_back265 driver.go_back266 end267 ##268 #269 # Move forward a single entry in the browser's history.270 #271 def go_forward272 driver.go_forward273 end274 ##275 #276 # Executes the given block within the context of a node. `within` takes the277 # same options as `find`, as well as a block. For the duration of the278 # block, any command to Capybara will be handled as though it were scoped279 # to the given element.280 #281 # within(:xpath, './/div[@id="delivery-address"]') do282 # fill_in('Street', with: '12 Main Street')283 # end284 #285 # Just as with `find`, if multiple elements match the selector given to286 # `within`, an error will be raised, and just as with `find`, this287 # behaviour can be controlled through the `:match` and `:exact` options.288 #289 # It is possible to omit the first parameter, in that case, the selector is290 # assumed to be of the type set in Capybara.default_selector.291 #292 # within('div#delivery-address') do293 # fill_in('Street', with: '12 Main Street')294 # end295 #296 # Note that a lot of uses of `within` can be replaced more succinctly with297 # chaining:298 #299 # find('div#delivery-address').fill_in('Street', with: '12 Main Street')300 #301 # @overload within(*find_args)302 # @param (see Capybara::Node::Finders#all)303 #304 # @overload within(a_node)305 # @param [Capybara::Node::Base] a_node The node in whose scope the block should be evaluated306 #307 # @raise [Capybara::ElementNotFound] If the scope can't be found before time expires308 #309 def within(*args)310 new_scope = if args.first.is_a?(Capybara::Node::Base) then args.first else find(*args) end311 begin312 scopes.push(new_scope)313 yield314 ensure315 scopes.pop316 end317 end318 alias_method :within_element, :within319 ##320 #321 # Execute the given block within the a specific fieldset given the id or legend of that fieldset.322 #323 # @param [String] locator Id or legend of the fieldset324 #325 def within_fieldset(locator)326 within :fieldset, locator do327 yield328 end329 end330 ##331 #332 # Execute the given block within the a specific table given the id or caption of that table.333 #334 # @param [String] locator Id or caption of the table335 #336 def within_table(locator)337 within :table, locator do338 yield339 end340 end341 ##342 #343 # Switch to the given frame344 #345 # 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.346 # Capybara::Session#within_frame is preferred over this method and should be used when possible.347 # May not be supported by all drivers.348 #349 # @overload switch_to_frame(element)350 # @param [Capybara::Node::Element] iframe/frame element to switch to351 # @overload switch_to_frame(:parent)352 # Switch to the parent element353 # @overload switch_to_frame(:top)354 # Switch to the top level document355 #356 def switch_to_frame(frame)357 case frame358 when Capybara::Node::Element359 driver.switch_to_frame(frame)360 scopes.push(:frame)361 when :parent362 raise Capybara::ScopeError, "`switch_to_frame(:parent)` cannot be called from inside a descendant frame's "\363 "`within` block." if scopes.last() != :frame364 scopes.pop365 driver.switch_to_frame(:parent)366 when :top367 idx = scopes.index(:frame)368 if idx369 raise Capybara::ScopeError, "`switch_to_frame(:top)` cannot be called from inside a descendant frame's "\370 "`within` block." if scopes.slice(idx..-1).any? {|scope| ![:frame, nil].include?(scope)}371 scopes.slice!(idx..-1)372 driver.switch_to_frame(:top)373 end374 end375 end376 ##377 #378 # Execute the given block within the given iframe using given frame, frame name/id or index.379 # May not be supported by all drivers.380 #381 # @overload within_frame(element)382 # @param [Capybara::Node::Element] frame element383 # @overload within_frame([kind = :frame], locator, options = {})384 # @param [Symobl] kind Optional selector type (:css, :xpath, :field, etc.) - Defaults to :frame385 # @param [String] locator The locator for the given selector kind. For :frame this is the name/id of a frame/iframe element386 # @overload within_frame(index)387 # @param [Integer] index index of a frame (0 based)388 def within_frame(*args)389 frame = _find_frame(*args)390 begin391 switch_to_frame(frame)392 begin393 yield394 ensure395 switch_to_frame(:parent)396 end397 rescue Capybara::NotSupportedByDriverError398 # Support older driver frame API for now399 if driver.respond_to?(:within_frame)400 begin401 scopes.push(:frame)402 driver.within_frame(frame) do403 yield404 end405 ensure406 scopes.pop407 end408 else409 raise410 end411 end412 end413 ##414 # @return [Capybara::Window] current window415 #416 def current_window417 Window.new(self, driver.current_window_handle)418 end419 ##420 # Get all opened windows.421 # The order of windows in returned array is not defined.422 # The driver may sort windows by their creation time but it's not required.423 #424 # @return [Array<Capybara::Window>] an array of all windows425 #426 def windows427 driver.window_handles.map do |handle|428 Window.new(self, handle)429 end430 end431 ##432 # Open new window.433 # Current window doesn't change as the result of this call.434 # It should be switched to explicitly.435 #436 # @return [Capybara::Window] window that has been opened437 #438 def open_new_window439 window_opened_by do440 driver.open_new_window441 end442 end443 ##444 # @overload switch_to_window(&block)445 # Switches to the first window for which given block returns a value other than false or nil.446 # If window that matches block can't be found, the window will be switched back and `WindowError` will be raised.447 # @example448 # window = switch_to_window { title == 'Page title' }449 # @raise [Capybara::WindowError] if no window matches given block450 # @overload switch_to_window(window)451 # @param window [Capybara::Window] window that should be switched to452 # @raise [Capybara::Driver::Base#no_such_window_error] if nonexistent (e.g. closed) window was passed453 #454 # @return [Capybara::Window] window that has been switched to455 # @raise [Capybara::ScopeError] if this method is invoked inside `within` or456 # `within_frame` methods457 # @raise [ArgumentError] if both or neither arguments were provided458 #459 def switch_to_window(window = nil, options= {}, &window_locator)460 options, window = window, nil if window.is_a? Hash461 block_given = block_given?462 if window && block_given463 raise ArgumentError, "`switch_to_window` can take either a block or a window, not both"464 elsif !window && !block_given465 raise ArgumentError, "`switch_to_window`: either window or block should be provided"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) }...

Full Screen

Full Screen

capybara-screenshot.rb

Source:capybara-screenshot.rb Github

copy

Full Screen

...3# class << self4# attr_accessor :autosave_on_failure5# attr_accessor :registered_drivers6# attr_accessor :filename_prefix_formatters7# attr_accessor :append_screenshot_path8# end9#10# self.autosave_on_failure = true11# self.registered_drivers = {}12# self.filename_prefix_formatters = {}13# self.append_screenshot_path = true14#15# def self.screenshot_and_save_page16# saver = Saver.new(Capybara, Capybara.page)17# saver.save18# {:html => saver.html_path, :image => saver.screenshot_path}19# end20#21# def self.screenshot_and_open_image22# require "launchy"23#24# saver = Saver.new(Capybara, Capybara.page, false)25# saver.save26# Launchy.open saver.screenshot_path27# {:html => nil, :image => saver.screenshot_path}28# end29#30# class << self31# alias screen_shot_and_save_page screenshot_and_save_page32# alias screen_shot_and_open_image screenshot_and_open_image33# end34#35# def self.filename_prefix_for(test_type, test)36# filename_prefix_formatters.fetch(test_type) { |key|37# filename_prefix_formatters[:default]38# }.call(test)39# end40#41# def self.capybara_root42# return @capybara_root if defined?(@capybara_root)43# #If the path isn't set, default to the current directory44# capybara_tmp_path = Capybara.save_and_open_page || '.'45#46# @capybara = if defined?(::Rails)47# ::Rails.root.join capybara_tmp_path48# elsif defined?(Padrino)49# Padrino.root capybara_tmp_path50# elsif defined?(Sinatra)51# File.join(Sinatra::Application.root, capybara_tmp_path)52# else53# capybara_tmp_path54# end.to_s55# end56#57# def self.register_driver(driver, &block)58# self.registered_drivers[driver] = block59# end60#61# def self.register_filename_prefix_formatter(test_type, &block)62# self.filename_prefix_formatters[test_type] = block63# end64# end65# end66#67# # Register driver renderers68# Capybara::Screenshot.class_eval do69# register_driver(:default) do |driver, path|70# driver.render(path)71# end72#73# register_driver(:rack_test) do |driver, path|74# warn "Rack::Test capybara driver has no ability to output screen shots. Skipping."75# end76#77# register_driver(:selenium) do |driver, path|78# driver.browser.save_screenshot(path)79# end80#81# register_driver(:poltergeist) do |driver, path|82# driver.render(path, :full => true)83# end84#85# register_driver(:webkit) do |driver, path|86# if driver.respond_to?(:save_screenshot)87# driver.save_screenshot(path)88# else89# driver.render(path)90# end91# end92#93# register_driver(:webkit_debug) do |driver, path|94# driver.render(path)95# end96#97# register_driver(:terminus) do |driver, path|98# driver.save_screenshot(path) if driver.respond_to?(:save_screenshot)99# end100# end101#102# # Register filename prefix formatters103# Capybara::Screenshot.class_eval do104# register_filename_prefix_formatter(:default) do |test|105# 'screenshot'106# end107# end108#109# require 'capybara/dsl'110# require 'capybara/util/save_and_open_page' if Capybara::VERSION.match(/^\d+/)[0] == '1' # no longer needed in Capybara version 2111#112# require 'capybara-screenshot/saver'...

Full Screen

Full Screen

path

Using AI Code Generation

copy

Full Screen

1puts page.find(:css, 'a').path2puts page.find(:css, 'a').path3puts page.find(:css, 'a').text4puts page.find(:css, 'a').path5puts page.find(:css, 'a').text6puts page.find(:css, 'a').text

Full Screen

Full Screen

path

Using AI Code Generation

copy

Full Screen

1visit('/')2path = page.driver.path('/')3visit('/')

Full Screen

Full Screen

path

Using AI Code Generation

copy

Full Screen

1 visit('/')2 find(:xpath, '/html/body/div/div[4]/form/div[2]/div[1]/div[1]/div/div[2]/input').set 'Hello World'3 find(:xpath, '/html/body/div/div[4]/form/div[2]/div[1]/div[3]/center/input[1]').click4 visit('/')5 find(:xpath, '/html/body/div/div[4]/form/div[2]/div[1]/div[1]/div/div[2]/input').set 'Hello World'6 find(:xpath, '/html/body/div/div[4]/form/div[2]/div[1]/div[3]/center/input[1]').click

Full Screen

Full Screen

path

Using AI Code Generation

copy

Full Screen

1Capybara.visit('/')2Capybara.fill_in('q', :with => 'ruby')3Capybara.click_button('Google Search')4Capybara.path('/search')5Capybara.save_screenshot('google.png')6Capybara.path('/search')

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.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful