repo stringlengths 5 92 | file_url stringlengths 80 287 | file_path stringlengths 5 197 | content stringlengths 0 32.8k | language stringclasses 1 value | license stringclasses 7 values | commit_sha stringlengths 40 40 | retrieved_at stringdate 2026-01-04 15:37:27 2026-01-04 17:58:21 | truncated bool 2 classes |
|---|---|---|---|---|---|---|---|---|
teamcapybara/capybara | https://github.com/teamcapybara/capybara/blob/b3325b198464b806f07ec2011ceb532d6d5cf4ab/spec/rspec/features_spec.rb | spec/rspec/features_spec.rb | # frozen_string_literal: true
# rubocop:disable RSpec/MultipleDescribes
require 'spec_helper'
require 'capybara/rspec'
# rubocop:disable RSpec/InstanceVariable
RSpec.configuration.before(:each, file_path: './spec/rspec/features_spec.rb') do
@in_filtered_hook = true
end
feature "Capybara's feature DSL" do
background do
@in_background = true
end
scenario 'includes Capybara' do
visit('/')
expect(page).to have_content('Hello world!')
end
scenario 'preserves description' do |ex|
expect(ex.metadata[:full_description])
.to eq("Capybara's feature DSL preserves description")
end
scenario 'allows driver switching', driver: :selenium do
expect(Capybara.current_driver).to eq(:selenium)
end
scenario 'runs background' do
expect(@in_background).to be_truthy
end
scenario 'runs hooks filtered by file path' do
expect(@in_filtered_hook).to be_truthy
end
scenario "doesn't pollute the Object namespace" do
expect(Object.new).not_to respond_to(:feature)
end
feature 'nested features' do
scenario 'work as expected' do
visit '/'
expect(page).to have_content 'Hello world!'
end
scenario 'are marked in the metadata as capybara_feature' do |ex|
expect(ex.metadata[:capybara_feature]).to be_truthy
end
scenario 'have a type of :feature' do |ex|
expect(ex.metadata[:type]).to eq :feature
end
end
end
# rubocop:enable RSpec/InstanceVariable
feature 'given and given! aliases to let and let!' do
given(:value) { :available }
given!(:value_in_background) { :available }
background do
expect(value_in_background).to be(:available)
end
scenario 'given and given! work as intended' do
expect(value).to be(:available)
expect(value_in_background).to be(:available)
end
end
feature "Capybara's feature DSL with driver", driver: :culerity do
scenario 'switches driver' do
expect(Capybara.current_driver).to eq(:culerity)
end
end
# rubocop:disable RSpec/RepeatedExample
xfeature 'if xfeature aliases to pending then' do
scenario "this should be 'temporarily disabled with xfeature'" do
# dummy
end
scenario "this also should be 'temporarily disabled with xfeature'" do
# dummy
end
end
ffeature 'if ffeature aliases focused tag then' do # rubocop:disable RSpec/Focus
scenario 'scenario inside this feature has metatag focus tag' do |example|
expect(example.metadata[:focus]).to be true
end
scenario 'other scenarios also has metatag focus tag' do |example|
expect(example.metadata[:focus]).to be true
end
end
# rubocop:enable RSpec/RepeatedExample, RSpec/MultipleDescribes
| ruby | MIT | b3325b198464b806f07ec2011ceb532d6d5cf4ab | 2026-01-04T15:38:10.098638Z | false |
teamcapybara/capybara | https://github.com/teamcapybara/capybara/blob/b3325b198464b806f07ec2011ceb532d6d5cf4ab/spec/rspec/views_spec.rb | spec/rspec/views_spec.rb | # frozen_string_literal: true
require 'spec_helper'
RSpec.describe 'capybara/rspec', type: :view do
it 'allows matchers to be used on strings' do
html = %(<h1>Test header</h1>)
expect(html).to have_css('h1', text: 'Test header')
end
it "doesn't include RSpecMatcherProxies" do
expect(self.class.ancestors).not_to include(Capybara::RSpecMatcherProxies)
end
end
| ruby | MIT | b3325b198464b806f07ec2011ceb532d6d5cf4ab | 2026-01-04T15:38:10.098638Z | false |
teamcapybara/capybara | https://github.com/teamcapybara/capybara/blob/b3325b198464b806f07ec2011ceb532d6d5cf4ab/spec/rspec/scenarios_spec.rb | spec/rspec/scenarios_spec.rb | # frozen_string_literal: true
# rubocop:disable RSpec/MultipleDescribes
require 'spec_helper'
require 'capybara/rspec'
RSpec.configuration.before(:each, file_path: './spec/rspec/scenarios_spec.rb') do
@in_filtered_hook = true
end
feature 'if fscenario aliases focused tag then' do
fscenario 'scenario should have focused meta tag' do |example| # rubocop:disable RSpec/Focus
expect(example.metadata[:focus]).to be true
end
end
feature 'if xscenario aliases to pending then' do
xscenario "this test should be 'temporarily disabled with xscenario'" do # rubocop:disable RSpec/PendingWithoutReason
end
end
# rubocop:enable RSpec/MultipleDescribes
| ruby | MIT | b3325b198464b806f07ec2011ceb532d6d5cf4ab | 2026-01-04T15:38:10.098638Z | false |
teamcapybara/capybara | https://github.com/teamcapybara/capybara/blob/b3325b198464b806f07ec2011ceb532d6d5cf4ab/spec/fixtures/selenium_driver_rspec_failure.rb | spec/fixtures/selenium_driver_rspec_failure.rb | # frozen_string_literal: true
require 'spec_helper'
require 'selenium-webdriver'
RSpec.describe Capybara::Selenium::Driver do
it 'should exit with a non-zero exit status' do
options = { browser: ENV.fetch('SELENIUM_BROWSER', :firefox).to_sym }
browser = described_class.new(TestApp, options).browser
expect(browser).to be_truthy
expect(true).to be(false) # rubocop:disable RSpec/ExpectActual
end
end
| ruby | MIT | b3325b198464b806f07ec2011ceb532d6d5cf4ab | 2026-01-04T15:38:10.098638Z | false |
teamcapybara/capybara | https://github.com/teamcapybara/capybara/blob/b3325b198464b806f07ec2011ceb532d6d5cf4ab/spec/fixtures/selenium_driver_rspec_success.rb | spec/fixtures/selenium_driver_rspec_success.rb | # frozen_string_literal: true
require 'spec_helper'
require 'selenium-webdriver'
RSpec.describe Capybara::Selenium::Driver do
it 'should exit with a zero exit status' do
options = { browser: ENV.fetch('SELENIUM_BROWSER', :firefox).to_sym }
browser = described_class.new(TestApp, **options).browser
expect(browser).to be_truthy
expect(true).to be(true) # rubocop:disable RSpec/ExpectActual,RSpec/IdenticalEqualityAssertion
end
end
| ruby | MIT | b3325b198464b806f07ec2011ceb532d6d5cf4ab | 2026-01-04T15:38:10.098638Z | false |
teamcapybara/capybara | https://github.com/teamcapybara/capybara/blob/b3325b198464b806f07ec2011ceb532d6d5cf4ab/lib/capybara.rb | lib/capybara.rb | # frozen_string_literal: true
require 'timeout'
require 'nokogiri'
require 'xpath'
require 'forwardable'
require 'capybara/config'
require 'capybara/registration_container'
module Capybara
class CapybaraError < StandardError; end
class DriverNotFoundError < CapybaraError; end
class FrozenInTime < CapybaraError; end
class ElementNotFound < CapybaraError; end
class ModalNotFound < CapybaraError; end
class Ambiguous < ElementNotFound; end
class ExpectationNotMet < ElementNotFound; end
class FileNotFound < CapybaraError; end
class UnselectNotAllowed < CapybaraError; end
class NotSupportedByDriverError < CapybaraError; end
class InfiniteRedirectError < CapybaraError; end
class ScopeError < CapybaraError; end
class WindowError < CapybaraError; end
class ReadOnlyElementError < CapybaraError; end
class << self
extend Forwardable
# DelegateCapybara global configurations
# @!method app
# See {Capybara.configure}
# @!method reuse_server
# See {Capybara.configure}
# @!method threadsafe
# See {Capybara.configure}
# @!method server
# See {Capybara.configure}
# @!method default_driver
# See {Capybara.configure}
# @!method javascript_driver
# See {Capybara.configure}
# @!method use_html5_parsing
# See {Capybara.configure}
Config::OPTIONS.each do |method|
def_delegators :config, method, "#{method}="
end
# Delegate Capybara global configurations
# @!method default_selector
# See {Capybara.configure}
# @!method default_max_wait_time
# See {Capybara.configure}
# @!method app_host
# See {Capybara.configure}
# @!method always_include_port
# See {Capybara.configure}
SessionConfig::OPTIONS.each do |method|
def_delegators :config, method, "#{method}="
end
##
#
# Configure Capybara to suit your needs.
#
# Capybara.configure do |config|
# config.run_server = false
# config.app_host = 'http://www.google.com'
# end
#
# #### Configurable options
#
# - **use_html5_parsing** (Boolean = `false`) - When Nokogiri >= 1.12.0 or `nokogumbo` is installed, whether HTML5 parsing will be used for HTML strings.
# - **always_include_port** (Boolean = `false`) - Whether the Rack server's port should automatically be inserted into every visited URL
# unless another port is explicitly specified.
# - **app_host** (String, `nil`) - The default host to use when giving a relative URL to visit, must be a valid URL e.g. `http://www.example.com`.
# - **asset_host** (String = `nil`) - Where dynamic assets are hosted - will be prepended to relative asset locations if present.
# - **automatic_label_click** (Boolean = `false`) - Whether {Capybara::Node::Element#choose Element#choose}, {Capybara::Node::Element#check Element#check},
# {Capybara::Node::Element#uncheck Element#uncheck} will attempt to click the associated `<label>` element if the checkbox/radio button are non-visible.
# - **automatic_reload** (Boolean = `true`) - Whether to automatically reload elements as Capybara is waiting.
# - **default_max_wait_time** (Numeric = `2`) - The maximum number of seconds to wait for asynchronous processes to finish.
# - **default_normalize_ws** (Boolean = `false`) - Whether text predicates and matchers use normalize whitespace behavior.
# - **default_retry_interval** (Numeric = `0.01`) - The number of seconds to delay the next check in asynchronous processes.
# - **default_selector** (`:css`, `:xpath` = `:css`) - Methods which take a selector use the given type by default. See also {Capybara::Selector}.
# - **default_set_options** (Hash = `{}`) - The default options passed to {Capybara::Node::Element#set Element#set}.
# - **enable_aria_label** (Boolean = `false`) - Whether fields, links, and buttons will match against `aria-label` attribute.
# - **enable_aria_role** (Boolean = `false`) - Selectors will check for relevant aria role (currently only `button`).
# - **exact** (Boolean = `false`) - Whether locators are matched exactly or with substrings. Only affects selector conditions
# written using the `XPath#is` method.
# - **exact_text** (Boolean = `false`) - Whether the text matchers and `:text` filter match exactly or on substrings.
# - **ignore_hidden_elements** (Boolean = `true`) - Whether to ignore hidden elements on the page.
# - **match** (`:one`, `:first`, `:prefer_exact`, `:smart` = `:smart`) - The matching strategy to find nodes.
# - **predicates_wait** (Boolean = `true`) - Whether Capybara's predicate matchers use waiting behavior by default.
# - **raise_server_errors** (Boolean = `true`) - Should errors raised in the server be raised in the tests?
# - **reuse_server** (Boolean = `true`) - Whether to reuse the server thread between multiple sessions using the same app object.
# - **run_server** (Boolean = `true`) - Whether to start a Rack server for the given Rack app.
# - **save_path** (String = `Dir.pwd`) - Where to put pages saved through {Capybara::Session#save_page save_page}, {Capybara::Session#save_screenshot save_screenshot},
# {Capybara::Session#save_and_open_page save_and_open_page}, or {Capybara::Session#save_and_open_screenshot save_and_open_screenshot}.
# - **server** (Symbol = `:default` (which uses puma)) - The name of the registered server to use when running the app under test.
# - **server_port** (Integer) - The port Capybara will run the application server on, if not specified a random port will be used.
# - **server_host** (String = "127.0.0.1") - The IP address Capybara will bind the application server to. If the test application is to be accessed from an external host, you will want to change this to "0.0.0.0" or to a more specific IP address that your test client can reach.
# - **server_errors** (Array\<Class> = `[Exception]`) - Error classes that should be raised in the tests if they are raised in the server
# and {configure raise_server_errors} is `true`.
# - **test_id** (Symbol, String, `nil` = `nil`) - Optional attribute to match locator against with built-in selectors along with id.
# - **threadsafe** (Boolean = `false`) - Whether sessions can be configured individually.
# - **w3c_click_offset** (Boolean = 'true') - Whether click offsets should be from element center (true) or top left (false)
#
# #### DSL Options
#
# When using `capybara/dsl`, the following options are also available:
#
# - **default_driver** (Symbol = `:rack_test`) - The name of the driver to use by default.
# - **javascript_driver** (Symbol = `:selenium`) - The name of a driver to use for JavaScript enabled tests.
#
def configure
yield config
end
##
#
# Register a new driver for Capybara.
#
# Capybara.register_driver :rack_test do |app|
# Capybara::RackTest::Driver.new(app)
# end
#
# @param [Symbol] name The name of the new driver
# @yield [app] This block takes a rack app and returns a Capybara driver
# @yieldparam [<Rack>] app The rack application that this driver runs against. May be nil.
# @yieldreturn [Capybara::Driver::Base] A Capybara driver instance
#
def register_driver(name, &block)
drivers.send(:register, name, block)
end
##
#
# Register a new server for Capybara.
#
# Capybara.register_server :webrick do |app, port, host|
# require 'rack/handler/webrick'
# Rack::Handler::WEBrick.run(app, ...)
# end
#
# @param [Symbol] name The name of the new driver
# @yield [app, port, host] This block takes a rack app and a port and returns a rack server listening on that port
# @yieldparam [<Rack>] app The rack application that this server will contain.
# @yieldparam port The port number the server should listen on
# @yieldparam host The host/ip to bind to
#
def register_server(name, &block)
servers.send(:register, name.to_sym, block)
end
##
#
# Add a new selector to Capybara. Selectors can be used by various methods in Capybara
# to find certain elements on the page in a more convenient way. For example adding a
# selector to find certain table rows might look like this:
#
# Capybara.add_selector(:row) do
# xpath { |num| ".//tbody/tr[#{num}]" }
# end
#
# This makes it possible to use this selector in a variety of ways:
#
# find(:row, 3)
# page.find('table#myTable').find(:row, 3).text
# page.find('table#myTable').has_selector?(:row, 3)
# within(:row, 3) { expect(page).to have_content('$100.000') }
#
# Here is another example:
#
# Capybara.add_selector(:id) do
# xpath { |id| XPath.descendant[XPath.attr(:id) == id.to_s] }
# end
#
# Note that this particular selector already ships with Capybara.
#
# @param [Symbol] name The name of the selector to add
# @yield A block executed in the context of the new {Capybara::Selector}
#
def add_selector(name, **options, &block)
Capybara::Selector.add(name, **options, &block)
end
##
#
# Modify a selector previously created by {Capybara.add_selector}.
# For example, adding a new filter to the :button selector to filter based on
# button style (a class) might look like this
#
# Capybara.modify_selector(:button) do
# filter (:btn_style, valid_values: [:primary, :secondary]) { |node, style| node[:class].split.include? "btn-#{style}" }
# end
#
#
# @param [Symbol] name The name of the selector to modify
# @yield A block executed in the context of the existing {Capybara::Selector}
#
def modify_selector(name, &block)
Capybara::Selector.update(name, &block)
end
def drivers
@drivers ||= RegistrationContainer.new
end
def servers
@servers ||= RegistrationContainer.new
end
# Wraps the given string, which should contain an HTML document or fragment
# in a {Capybara::Node::Simple} which exposes all {Capybara::Node::Matchers},
# {Capybara::Node::Finders} and {Capybara::Node::DocumentMatchers}. This allows you to query
# any string containing HTML in the exact same way you would query the current document in a Capybara
# session.
#
# @example A single element
# node = Capybara.string('<a href="foo">bar</a>')
# anchor = node.first('a')
# anchor[:href] #=> 'foo'
# anchor.text #=> 'bar'
#
# @example Multiple elements
# node = Capybara.string <<-HTML
# <ul>
# <li id="home">Home</li>
# <li id="projects">Projects</li>
# </ul>
# HTML
#
# node.find('#projects').text # => 'Projects'
# node.has_selector?('li#home', text: 'Home')
# node.has_selector?('#projects')
# node.find('ul').find('li:first-child').text # => 'Home'
#
# @param [String] html An html fragment or document
# @return [Capybara::Node::Simple] A node which has Capybara's finders and matchers
#
def string(html)
Capybara::Node::Simple.new(html)
end
##
#
# Runs Capybara's default server for the given application and port
# under most circumstances you should not have to call this method
# manually.
#
# @param [Rack Application] app The rack application to run
# @param [Integer] port The port to run the application on
#
def run_default_server(app, port)
servers[:puma].call(app, port, server_host)
end
##
#
# @return [Symbol] The name of the driver currently in use
#
def current_driver
if threadsafe
Thread.current.thread_variable_get :capybara_current_driver
else
@current_driver
end || default_driver
end
alias_method :mode, :current_driver
def current_driver=(name)
if threadsafe
Thread.current.thread_variable_set :capybara_current_driver, name
else
@current_driver = name
end
end
##
#
# Use the default driver as the current driver
#
def use_default_driver
self.current_driver = nil
end
##
#
# Yield a block using a specific driver
#
def using_driver(driver)
previous_driver = Capybara.current_driver
Capybara.current_driver = driver
yield
ensure
self.current_driver = previous_driver
end
##
#
# Yield a block using a specific wait time
#
def using_wait_time(seconds)
previous_wait_time = Capybara.default_max_wait_time
Capybara.default_max_wait_time = seconds
yield
ensure
Capybara.default_max_wait_time = previous_wait_time
end
##
#
# The current {Capybara::Session} based on what is set as {app} and {current_driver}.
#
# @return [Capybara::Session] The currently used session
#
def current_session
specified_session || session_pool["#{current_driver}:#{session_name}:#{app.object_id}"]
end
##
#
# Reset sessions, cleaning out the pool of sessions. This will remove any session information such
# as cookies.
#
def reset_sessions!
# reset in reverse so sessions that started servers are reset last
session_pool.reverse_each { |_mode, session| session.reset! }
end
alias_method :reset!, :reset_sessions!
##
#
# The current session name.
#
# @return [Symbol] The name of the currently used session.
#
def session_name
if threadsafe
Thread.current.thread_variable_get(:capybara_session_name) ||
Thread.current.thread_variable_set(:capybara_session_name, :default)
else
@session_name ||= :default
end
end
def session_name=(name)
if threadsafe
Thread.current.thread_variable_set :capybara_session_name, name
else
@session_name = name
end
end
##
#
# Yield a block using a specific session name or {Capybara::Session} instance.
#
def using_session(name_or_session, &block)
previous_session = current_session
previous_session_info = {
specified_session: specified_session,
session_name: session_name,
current_driver: current_driver,
app: app
}
self.specified_session = self.session_name = nil
if name_or_session.is_a? Capybara::Session
self.specified_session = name_or_session
else
self.session_name = name_or_session
end
if block.arity.zero?
yield
else
yield current_session, previous_session
end
ensure
self.session_name, self.specified_session = previous_session_info.values_at(:session_name, :specified_session)
self.current_driver, self.app = previous_session_info.values_at(:current_driver, :app) if threadsafe
end
##
#
# Parse raw html into a document using Nokogiri, and adjust textarea contents as defined by the spec.
#
# @param [String] html The raw html
# @return [Nokogiri::HTML::Document] HTML document
#
def HTML(html) # rubocop:disable Naming/MethodName
# Nokogiri >= 1.12.0 or Nokogumbo installed and allowed for use
html_parser, using_html5 = if defined?(Nokogiri::HTML5) && Capybara.use_html5_parsing
[Nokogiri::HTML5, true]
else
[defined?(Nokogiri::HTML4) ? Nokogiri::HTML4 : Nokogiri::HTML, false]
end
html_parser.parse(html).tap do |document|
document.xpath('//template').each do |template|
# template elements content is not part of the document
template.inner_html = ''
end
document.xpath('//textarea').each do |textarea|
# The Nokogiri HTML5 parser already returns spec compliant contents
textarea['_capybara_raw_value'] = using_html5 ? textarea.content : textarea.content.delete_prefix("\n")
end
end
end
def session_options
config.session_options
end
private
def config
@config ||= Capybara::Config.new
end
def session_pool
@session_pool ||= Hash.new do |hash, name|
hash[name] = Capybara::Session.new(current_driver, app)
end
end
def specified_session
if threadsafe
Thread.current.thread_variable_get :capybara_specified_session
else
@specified_session ||= nil
end
end
def specified_session=(session)
if threadsafe
Thread.current.thread_variable_set :capybara_specified_session, session
else
@specified_session = session
end
end
end
self.default_driver = nil
self.current_driver = nil
self.server_host = nil
module Driver; end
module RackTest; end
module Selenium; end
require 'capybara/helpers'
require 'capybara/session'
require 'capybara/window'
require 'capybara/server'
require 'capybara/selector'
require 'capybara/result'
require 'capybara/version'
require 'capybara/queries/base_query'
require 'capybara/queries/selector_query'
require 'capybara/queries/text_query'
require 'capybara/queries/title_query'
require 'capybara/queries/current_path_query'
require 'capybara/queries/match_query'
require 'capybara/queries/ancestor_query'
require 'capybara/queries/sibling_query'
require 'capybara/queries/style_query'
require 'capybara/queries/active_element_query'
require 'capybara/node/finders'
require 'capybara/node/matchers'
require 'capybara/node/actions'
require 'capybara/node/document_matchers'
require 'capybara/node/simple'
require 'capybara/node/base'
require 'capybara/node/element'
require 'capybara/node/document'
require 'capybara/driver/base'
require 'capybara/driver/node'
require 'capybara/rack_test/driver'
require 'capybara/rack_test/node'
require 'capybara/rack_test/form'
require 'capybara/rack_test/browser'
require 'capybara/rack_test/css_handlers'
require 'capybara/selenium/node'
require 'capybara/selenium/driver'
end
require 'capybara/registrations/servers'
require 'capybara/registrations/drivers'
Capybara.configure do |config|
config.always_include_port = false
config.run_server = true
config.server = :default
config.default_selector = :css
config.default_max_wait_time = 2
config.default_retry_interval = 0.01
config.ignore_hidden_elements = true
config.default_host = 'http://www.example.com'
config.automatic_reload = true
config.match = :smart
config.exact = false
config.exact_text = false
config.raise_server_errors = true
config.server_errors = [Exception]
config.visible_text_only = false
config.automatic_label_click = false
config.enable_aria_label = false
config.enable_aria_role = false
config.reuse_server = true
config.default_set_options = {}
config.test_id = nil
config.predicates_wait = true
config.default_normalize_ws = false
config.use_html5_parsing = false
config.w3c_click_offset = true
end
| ruby | MIT | b3325b198464b806f07ec2011ceb532d6d5cf4ab | 2026-01-04T15:38:10.098638Z | false |
teamcapybara/capybara | https://github.com/teamcapybara/capybara/blob/b3325b198464b806f07ec2011ceb532d6d5cf4ab/lib/capybara/selector.rb | lib/capybara/selector.rb | # frozen_string_literal: true
require 'capybara/selector/xpath_extensions'
require 'capybara/selector/selector'
require 'capybara/selector/definition'
#
# All Selectors below support the listed selector specific filters in addition to the following system-wide filters
# * :id (String, Regexp, XPath::Expression) - Matches the id attribute
# * :class (String, Array<String | Regexp>, Regexp, XPath::Expression) - Matches the class(es) provided
# * :style (String, Regexp, Hash<String, String>) - Match on elements style
# * :above (Element) - Match elements above the passed element on the page
# * :below (Element) - Match elements below the passed element on the page
# * :left_of (Element) - Match elements left of the passed element on the page
# * :right_of (Element) - Match elements right of the passed element on the page
# * :near (Element) - Match elements near (within 50px) the passed element on the page
# * :focused (Boolean) - Match elements with focus (requires driver support)
#
# ### Built-in Selectors
#
# * **:xpath** - Select elements by XPath expression
# * Locator: An XPath expression
#
# ```ruby
# page.html # => '<input>'
#
# page.find :xpath, './/input'
# ```
#
# * **:css** - Select elements by CSS selector
# * Locator: A CSS selector
#
# ```ruby
# page.html # => '<input>'
#
# page.find :css, 'input'
# ```
#
# * **:id** - Select element by id
# * Locator: (String, Regexp, XPath::Expression) The id of the element to match
#
# ```ruby
# page.html # => '<input id="field">'
#
# page.find :id, 'field'
# ```
#
# * **:field** - Select field elements (input [not of type submit, image, or hidden], textarea, select)
# * Locator: Matches against the id, {Capybara.configure test_id} attribute, name, placeholder, or
# associated label text
# * Filters:
# * :name (String, Regexp) - Matches the name attribute
# * :placeholder (String, Regexp) - Matches the placeholder attribute
# * :type (String) - Matches the type attribute of the field or element type for 'textarea' and 'select'
# * :readonly (Boolean) - Match on the element being readonly
# * :with (String, Regexp) - Matches the current value of the field
# * :checked (Boolean) - Match checked fields?
# * :unchecked (Boolean) - Match unchecked fields?
# * :disabled (Boolean, :all) - Match disabled field? (Default: false)
# * :multiple (Boolean) - Match fields that accept multiple values
# * :valid (Boolean) - Match fields that are valid/invalid according to HTML5 form validation
# * :validation_message (String, Regexp) - Matches the elements current validationMessage
#
# ```ruby
# page.html # => '<label for="article_title">Title</label>
# # <input id="article_title" name="article[title]" value="Hello world">'
#
# page.find :field, 'article_title'
# page.find :field, 'article[title]'
# page.find :field, 'Title'
# page.find :field, 'Title', type: 'text', with: 'Hello world'
# ```
#
# * **:fieldset** - Select fieldset elements
# * Locator: Matches id, {Capybara.configure test_id}, or contents of wrapped legend
# * Filters:
# * :legend (String) - Matches contents of wrapped legend
# * :disabled (Boolean) - Match disabled fieldset?
#
# ```ruby
# page.html # => '<fieldset disabled>
# # <legend>Fields (disabled)</legend>
# # </fieldset>'
#
# page.find :fieldset, 'Fields (disabled)', disabled: true
# ```
#
# * **:link** - Find links (`<a>` elements with an href attribute)
# * Locator: Matches the id, {Capybara.configure test_id}, or title attributes, or the string content of the link,
# or the alt attribute of a contained img element. By default this selector requires a link to have an href attribute.
# * Filters:
# * :title (String) - Matches the title attribute
# * :alt (String) - Matches the alt attribute of a contained img element
# * :href (String, Regexp, nil, false) - Matches the normalized href of the link, if nil will find `<a>` elements with no href attribute, if false ignores href presence
#
# ```ruby
# page.html # => '<a href="/">Home</a>'
#
# page.find :link, 'Home', href: '/'
#
# page.html # => '<a href="/"><img src="/logo.png" alt="The logo"></a>'
#
# page.find :link, 'The logo', href: '/'
# page.find :link, alt: 'The logo', href: '/'
# ```
#
# * **:button** - Find buttons ( input [of type submit, reset, image, button] or button elements )
# * Locator: Matches the id, {Capybara.configure test_id} attribute, name, value, or title attributes, string content of a button, or the alt attribute of an image type button or of a descendant image of a button
# * Filters:
# * :name (String, Regexp) - Matches the name attribute
# * :title (String) - Matches the title attribute
# * :value (String) - Matches the value of an input button
# * :type (String) - Matches the type attribute
# * :disabled (Boolean, :all) - Match disabled buttons (Default: false)
#
# ```ruby
# page.html # => '<button>Submit</button>'
#
# page.find :button, 'Submit'
#
# page.html # => '<button name="article[state]" value="draft">Save as draft</button>'
#
# page.find :button, 'Save as draft', name: 'article[state]', value: 'draft'
# ```
#
# * **:link_or_button** - Find links or buttons
# * Locator: See :link and :button selectors
# * Filters:
# * :disabled (Boolean, :all) - Match disabled buttons? (Default: false)
#
# ```ruby
# page.html # => '<a href="/">Home</a>'
#
# page.find :link_or_button, 'Home'
#
# page.html # => '<button>Submit</button>'
#
# page.find :link_or_button, 'Submit'
# ```
#
# * **:fillable_field** - Find text fillable fields ( textarea, input [not of type submit, image, radio, checkbox, hidden, file] )
# * Locator: Matches against the id, {Capybara.configure test_id} attribute, name, placeholder, or associated label text
# * Filters:
# * :name (String, Regexp) - Matches the name attribute
# * :placeholder (String, Regexp) - Matches the placeholder attribute
# * :with (String, Regexp) - Matches the current value of the field
# * :type (String) - Matches the type attribute of the field or element type for 'textarea'
# * :disabled (Boolean, :all) - Match disabled field? (Default: false)
# * :multiple (Boolean) - Match fields that accept multiple values
# * :valid (Boolean) - Match fields that are valid/invalid according to HTML5 form validation
# * :validation_message (String, Regexp) - Matches the elements current validationMessage
#
# ```ruby
# page.html # => '<label for="article_body">Body</label>
# # <textarea id="article_body" name="article[body]"></textarea>'
#
# page.find :fillable_field, 'article_body'
# page.find :fillable_field, 'article[body]'
# page.find :fillable_field, 'Body'
# page.find :field, 'Body', type: 'textarea'
# ```
#
# * **:radio_button** - Find radio buttons
# * Locator: Match id, {Capybara.configure test_id} attribute, name, or associated label text
# * Filters:
# * :name (String, Regexp) - Matches the name attribute
# * :checked (Boolean) - Match checked fields?
# * :unchecked (Boolean) - Match unchecked fields?
# * :disabled (Boolean, :all) - Match disabled field? (Default: false)
# * :option (String, Regexp) - Match the current value
# * :with - Alias of :option
#
# ```ruby
# page.html # => '<input type="radio" id="article_state_published" name="article[state]" value="published" checked>
# # <label for="article_state_published">Published</label>
# # <input type="radio" id="article_state_draft" name="article[state]" value="draft">
# # <label for="article_state_draft">Draft</label>'
#
# page.find :radio_button, 'article_state_published'
# page.find :radio_button, 'article[state]', option: 'published'
# page.find :radio_button, 'Published', checked: true
# page.find :radio_button, 'Draft', unchecked: true
# ```
#
# * **:checkbox** - Find checkboxes
# * Locator: Match id, {Capybara.configure test_id} attribute, name, or associated label text
# * Filters:
# * :name (String, Regexp) - Matches the name attribute
# * :checked (Boolean) - Match checked fields?
# * :unchecked (Boolean) - Match unchecked fields?
# * :disabled (Boolean, :all) - Match disabled field? (Default: false)
# * :with (String, Regexp) - Match the current value
# * :option - Alias of :with
#
# ```ruby
# page.html # => '<input type="checkbox" id="registration_terms" name="registration[terms]" value="true">
# # <label for="registration_terms">I agree to terms and conditions</label>'
#
# page.find :checkbox, 'registration_terms'
# page.find :checkbox, 'registration[terms]'
# page.find :checkbox, 'I agree to terms and conditions', unchecked: true
# ```
#
# * **:select** - Find select elements
# * Locator: Match id, {Capybara.configure test_id} attribute, name, placeholder, or associated label text
# * Filters:
# * :name (String, Regexp) - Matches the name attribute
# * :placeholder (String, Placeholder) - Matches the placeholder attribute
# * :disabled (Boolean, :all) - Match disabled field? (Default: false)
# * :multiple (Boolean) - Match fields that accept multiple values
# * :options (Array<String>) - Exact match options
# * :enabled_options (Array<String>) - Exact match enabled options
# * :disabled_options (Array<String>) - Exact match disabled options
# * :with_options (Array<String>) - Partial match options
# * :selected (String, Array<String>) - Match the selection(s)
# * :with_selected (String, Array<String>) - Partial match the selection(s)
#
# ```ruby
# page.html # => '<label for="article_category">Category</label>
# # <select id="article_category" name="article[category]">
# # <option value="General" checked></option>
# # <option value="Other"></option>
# # </select>'
#
# page.find :select, 'article_category'
# page.find :select, 'article[category]'
# page.find :select, 'Category'
# page.find :select, 'Category', selected: 'General'
# page.find :select, with_options: ['General']
# page.find :select, with_options: ['Other']
# page.find :select, options: ['General', 'Other']
# page.find :select, options: ['General'] # => raises Capybara::ElementNotFound
# ```
#
# * **:option** - Find option elements
# * Locator: Match text of option
# * Filters:
# * :disabled (Boolean) - Match disabled option
# * :selected (Boolean) - Match selected option
#
# ```ruby
# page.html # => '<option value="General" checked></option>
# # <option value="Disabled" disabled></option>
# # <option value="Other"></option>'
#
# page.find :option, 'General'
# page.find :option, 'General', selected: true
# page.find :option, 'Disabled', disabled: true
# page.find :option, 'Other', selected: false
# ```
#
# * **:datalist_input** - Find input field with datalist completion
# * Locator: Matches against the id, {Capybara.configure test_id} attribute, name,
# placeholder, or associated label text
# * Filters:
# * :name (String, Regexp) - Matches the name attribute
# * :placeholder (String, Regexp) - Matches the placeholder attribute
# * :disabled (Boolean, :all) - Match disabled field? (Default: false)
# * :options (Array<String>) - Exact match options
# * :with_options (Array<String>) - Partial match options
#
# ```ruby
# page.html # => '<label for="ice_cream_flavor">Flavor</label>
# # <input list="ice_cream_flavors" id="ice_cream_flavor" name="ice_cream[flavor]">
# # <datalist id="ice_cream_flavors">
# # <option value="Chocolate"></option>
# # <option value="Strawberry"></option>
# # <option value="Vanilla"></option>
# # </datalist>'
#
# page.find :datalist_input, 'ice_cream_flavor'
# page.find :datalist_input, 'ice_cream[flavor]'
# page.find :datalist_input, 'Flavor'
# page.find :datalist_input, with_options: ['Chocolate', 'Strawberry']
# page.find :datalist_input, options: ['Chocolate', 'Strawberry', 'Vanilla']
# page.find :datalist_input, options: ['Chocolate'] # => raises Capybara::ElementNotFound
# ```
#
# * **:datalist_option** - Find datalist option
# * Locator: Match text or value of option
# * Filters:
# * :disabled (Boolean) - Match disabled option
#
# ```ruby
# page.html # => '<datalist>
# # <option value="Chocolate"></option>
# # <option value="Strawberry"></option>
# # <option value="Vanilla"></option>
# # <option value="Forbidden" disabled></option>
# # </datalist>'
#
# page.find :datalist_option, 'Chocolate'
# page.find :datalist_option, 'Strawberry'
# page.find :datalist_option, 'Vanilla'
# page.find :datalist_option, 'Forbidden', disabled: true
# ```
#
# * **:file_field** - Find file input elements
# * Locator: Match id, {Capybara.configure test_id} attribute, name, or associated label text
# * Filters:
# * :name (String, Regexp) - Matches the name attribute
# * :disabled (Boolean, :all) - Match disabled field? (Default: false)
# * :multiple (Boolean) - Match field that accepts multiple values
#
# ```ruby
# page.html # => '<label for="article_banner_image">Banner Image</label>
# # <input type="file" id="article_banner_image" name="article[banner_image]">'
#
# page.find :file_field, 'article_banner_image'
# page.find :file_field, 'article[banner_image]'
# page.find :file_field, 'Banner Image'
# page.find :file_field, 'Banner Image', name: 'article[banner_image]'
# page.find :field, 'Banner Image', type: 'file'
# ```
#
# * **:label** - Find label elements
# * Locator: Match id, {Capybara.configure test_id}, or text contents
# * Filters:
# * :for (Element, String, Regexp) - The element or id of the element associated with the label
#
# ```ruby
# page.html # => '<label for="article_title">Title</label>
# # <input id="article_title" name="article[title]">'
#
# page.find :label, 'Title'
# page.find :label, 'Title', for: 'article_title'
# page.find :label, 'Title', for: page.find('article[title]')
# ```
#
# * **:table** - Find table elements
# * Locator: id, {Capybara.configure test_id}, or caption text of table
# * Filters:
# * :caption (String) - Match text of associated caption
# * :with_rows (Array<Array<String>>, Array<Hash<String, String>>) - Partial match `<td>` data - visibility of `<td>` elements is not considered
# * :rows (Array<Array<String>>) - Match all `<td>`s - visibility of `<td>` elements is not considered
# * :with_cols (Array<Array<String>>, Array<Hash<String, String>>) - Partial match `<td>` data - visibility of `<td>` elements is not considered
# * :cols (Array<Array<String>>) - Match all `<td>`s - visibility of `<td>` elements is not considered
#
# ```ruby
# page.html # => '<table>
# # <caption>A table</caption>
# # <tr>
# # <th>A</th>
# # <th>B</th>
# # </tr>
# # <tr>
# # <td>1</td>
# # <td>2</td>
# # </tr>
# # <tr>
# # <td>3</td>
# # <td>4</td>
# # </tr>
# # </table>'
#
# page.find :table, 'A table'
# page.find :table, with_rows: [
# { 'A' => '1', 'B' => '2' },
# { 'A' => '3', 'B' => '4' },
# ]
# page.find :table, with_rows: [
# ['1', '2'],
# ['3', '4'],
# ]
# page.find :table, rows: [
# { 'A' => '1', 'B' => '2' },
# { 'A' => '3', 'B' => '4' },
# ]
# page.find :table, rows: [
# ['1', '2'],
# ['3', '4'],
# ]
# page.find :table, rows: [ ['1', '2'] ] # => raises Capybara::ElementNotFound
# ```
#
# * **:table_row** - Find table row
# * Locator: Array<String>, Hash<String, String> table row `<td>` contents - visibility of `<td>` elements is not considered
#
# ```ruby
# page.html # => '<table>
# # <tr>
# # <th>A</th>
# # <th>B</th>
# # </tr>
# # <tr>
# # <td>1</td>
# # <td>2</td>
# # </tr>
# # <tr>
# # <td>3</td>
# # <td>4</td>
# # </tr>
# # </table>'
#
# page.find :table_row, 'A' => '1', 'B' => '2'
# page.find :table_row, 'A' => '3', 'B' => '4'
# ```
#
# * **:frame** - Find frame/iframe elements
# * Locator: Match id, {Capybara.configure test_id} attribute, or name
# * Filters:
# * :name (String) - Match name attribute
#
# ```ruby
# page.html # => '<iframe id="embed_frame" name="embed" src="https://example.com/embed"></iframe>'
#
# page.find :frame, 'embed_frame'
# page.find :frame, 'embed'
# page.find :frame, name: 'embed'
# ```
#
# * **:element**
# * Locator: Type of element ('div', 'a', etc) - if not specified defaults to '*'
# * Filters:
# * :\<any> (String, Regexp) - Match on any specified element attribute
#
# ```ruby
# page.html # => '<button type="button" role="menuitemcheckbox" aria-checked="true">Check me</button>
#
# page.find :element, 'button'
# page.find :element, type: 'button', text: 'Check me'
# page.find :element, role: 'menuitemcheckbox'
# page.find :element, role: /checkbox/, 'aria-checked': 'true'
# ```
#
class Capybara::Selector; end # rubocop:disable Lint/EmptyClass
Capybara::Selector::FilterSet.add(:_field) do
node_filter(:checked, :boolean) { |node, value| !(value ^ node.checked?) }
node_filter(:unchecked, :boolean) { |node, value| (value ^ node.checked?) }
node_filter(:disabled, :boolean, default: false, skip_if: :all) { |node, value| !(value ^ node.disabled?) }
node_filter(:valid, :boolean) { |node, value| node.evaluate_script('this.validity.valid') == value }
node_filter(:name) { |node, value| !value.is_a?(Regexp) || value.match?(node[:name]) }
node_filter(:placeholder) { |node, value| !value.is_a?(Regexp) || value.match?(node[:placeholder]) }
node_filter(:validation_message) do |node, msg|
vm = node[:validationMessage]
(msg.is_a?(Regexp) ? msg.match?(vm) : vm == msg.to_s).tap do |res|
add_error("Expected validation message to be #{msg.inspect} but was #{vm}") unless res
end
end
expression_filter(:name) do |xpath, val|
builder(xpath).add_attribute_conditions(name: val)
end
expression_filter(:placeholder) do |xpath, val|
builder(xpath).add_attribute_conditions(placeholder: val)
end
expression_filter(:disabled) { |xpath, val| val ? xpath : xpath[~XPath.attr(:disabled)] }
expression_filter(:multiple) { |xpath, val| xpath[val ? XPath.attr(:multiple) : ~XPath.attr(:multiple)] }
describe(:expression_filters) do |name: nil, placeholder: nil, disabled: nil, multiple: nil, **|
desc = +''
desc << ' that is not disabled' if disabled == false
desc << " with name #{name}" if name
desc << " with placeholder #{placeholder}" if placeholder
desc << ' with the multiple attribute' if multiple == true
desc << ' without the multiple attribute' if multiple == false
desc
end
describe(:node_filters) do |checked: nil, unchecked: nil, disabled: nil, valid: nil, validation_message: nil, **|
desc, states = +'', []
states << 'checked' if checked || (unchecked == false)
states << 'not checked' if unchecked || (checked == false)
states << 'disabled' if disabled == true
desc << " that is #{states.join(' and ')}" unless states.empty?
desc << ' that is valid' if valid == true
desc << ' that is invalid' if valid == false
desc << " with validation message #{validation_message.to_s.inspect}" if validation_message
desc
end
end
require 'capybara/selector/definition/xpath'
require 'capybara/selector/definition/css'
require 'capybara/selector/definition/id'
require 'capybara/selector/definition/field'
require 'capybara/selector/definition/fieldset'
require 'capybara/selector/definition/link'
require 'capybara/selector/definition/button'
require 'capybara/selector/definition/link_or_button'
require 'capybara/selector/definition/fillable_field'
require 'capybara/selector/definition/radio_button'
require 'capybara/selector/definition/checkbox'
require 'capybara/selector/definition/select'
require 'capybara/selector/definition/datalist_input'
require 'capybara/selector/definition/option'
require 'capybara/selector/definition/datalist_option'
require 'capybara/selector/definition/file_field'
require 'capybara/selector/definition/label'
require 'capybara/selector/definition/table'
require 'capybara/selector/definition/table_row'
require 'capybara/selector/definition/frame'
require 'capybara/selector/definition/element'
| ruby | MIT | b3325b198464b806f07ec2011ceb532d6d5cf4ab | 2026-01-04T15:38:10.098638Z | false |
teamcapybara/capybara | https://github.com/teamcapybara/capybara/blob/b3325b198464b806f07ec2011ceb532d6d5cf4ab/lib/capybara/cucumber.rb | lib/capybara/cucumber.rb | # frozen_string_literal: true
require 'capybara/dsl'
require 'capybara/rspec/matchers'
require 'capybara/rspec/matcher_proxies'
World(Capybara::DSL)
World(Capybara::RSpecMatchers)
After do
Capybara.reset_sessions!
end
Before do
Capybara.use_default_driver
end
Before '@javascript' do
Capybara.current_driver = Capybara.javascript_driver
end
Before do |scenario|
scenario.source_tag_names.each do |tag|
driver_name = tag.sub(/^@/, '').to_sym
Capybara.current_driver = driver_name if Capybara.drivers[driver_name]
end
end
| ruby | MIT | b3325b198464b806f07ec2011ceb532d6d5cf4ab | 2026-01-04T15:38:10.098638Z | false |
teamcapybara/capybara | https://github.com/teamcapybara/capybara/blob/b3325b198464b806f07ec2011ceb532d6d5cf4ab/lib/capybara/session.rb | lib/capybara/session.rb | # frozen_string_literal: true
require 'capybara/session/matchers'
require 'addressable/uri'
module Capybara
##
#
# The {Session} class represents a single user's interaction with the system. The {Session} can use
# any of the underlying drivers. A session can be initialized manually like this:
#
# session = Capybara::Session.new(:culerity, MyRackApp)
#
# The application given as the second argument is optional. When running Capybara against an external
# page, you might want to leave it out:
#
# session = Capybara::Session.new(:culerity)
# session.visit('http://www.google.com')
#
# When {Capybara.configure threadsafe} is `true` the sessions options will be initially set to the
# current values of the global options and a configuration block can be passed to the session initializer.
# For available options see {Capybara::SessionConfig::OPTIONS}:
#
# session = Capybara::Session.new(:driver, MyRackApp) do |config|
# config.app_host = "http://my_host.dev"
# end
#
# The {Session} provides a number of methods for controlling the navigation of the page, such as {#visit},
# {#current_path}, and so on. It also delegates a number of methods to a {Capybara::Document}, representing
# the current HTML document. This allows interaction:
#
# session.fill_in('q', with: 'Capybara')
# session.click_button('Search')
# expect(session).to have_content('Capybara')
#
# When using `capybara/dsl`, the {Session} is initialized automatically for you.
#
class Session
include Capybara::SessionMatchers
NODE_METHODS = %i[
all first attach_file text check choose scroll_to scroll_by
click double_click right_click
click_link_or_button click_button click_link
fill_in find find_all find_button find_by_id find_field find_link
has_content? has_text? has_css? has_no_content? has_no_text?
has_no_css? has_no_xpath? has_xpath? select uncheck
has_element? has_no_element?
has_link? has_no_link? has_button? has_no_button? has_field?
has_no_field? has_checked_field? has_unchecked_field?
has_no_table? has_table? unselect has_select? has_no_select?
has_selector? has_no_selector? click_on has_no_checked_field?
has_no_unchecked_field? query assert_selector assert_no_selector
assert_all_of_selectors assert_none_of_selectors assert_any_of_selectors
refute_selector assert_text assert_no_text
].freeze
# @api private
DOCUMENT_METHODS = %i[
title assert_title assert_no_title has_title? has_no_title?
].freeze
SESSION_METHODS = %i[
body html source current_url current_host current_path
execute_script evaluate_script evaluate_async_script visit refresh go_back go_forward send_keys
within within_element within_fieldset within_table within_frame switch_to_frame
current_window windows open_new_window switch_to_window within_window window_opened_by
save_page save_and_open_page save_screenshot
save_and_open_screenshot reset_session! response_headers
status_code current_scope
assert_current_path assert_no_current_path has_current_path? has_no_current_path?
].freeze + DOCUMENT_METHODS
MODAL_METHODS = %i[
accept_alert accept_confirm dismiss_confirm accept_prompt dismiss_prompt
].freeze
DSL_METHODS = NODE_METHODS + SESSION_METHODS + MODAL_METHODS
attr_reader :mode, :app, :server
attr_accessor :synchronized
def initialize(mode, app = nil)
if app && !app.respond_to?(:call)
raise TypeError, 'The second parameter to Session::new should be a rack app if passed.'
end
@@instance_created = true # rubocop:disable Style/ClassVars
@mode = mode
@app = app
if block_given?
raise 'A configuration block is only accepted when Capybara.threadsafe == true' unless Capybara.threadsafe
yield config
end
@server = if config.run_server && @app && driver.needs_server?
server_options = { port: config.server_port, host: config.server_host, reportable_errors: config.server_errors }
server_options[:extra_middleware] = [Capybara::Server::AnimationDisabler] if config.disable_animation
Capybara::Server.new(@app, **server_options).boot
end
@touched = false
end
def driver
@driver ||= begin
unless Capybara.drivers[mode]
other_drivers = Capybara.drivers.names.map(&:inspect)
raise Capybara::DriverNotFoundError, "no driver called #{mode.inspect} was found, available drivers: #{other_drivers.join(', ')}"
end
driver = Capybara.drivers[mode].call(app)
driver.session = self if driver.respond_to?(:session=)
driver
end
end
##
#
# Reset the session (i.e. remove cookies and navigate to blank page).
#
# This method does not:
#
# * accept modal dialogs if they are present (Selenium driver now does, others may not)
# * clear browser cache/HTML 5 local storage/IndexedDB/Web SQL database/etc.
# * modify state of the driver/underlying browser in any other way
#
# as doing so will result in performance downsides and it's not needed to do everything from the list above for most apps.
#
# If you want to do anything from the list above on a general basis you can:
#
# * write RSpec/Cucumber/etc. after hook
# * monkeypatch this method
# * use Ruby's `prepend` method
#
def reset!
if @touched
driver.reset!
@touched = false
switch_to_frame(:top) rescue nil # rubocop:disable Style/RescueModifier
@scopes = [nil]
end
@server&.wait_for_pending_requests
raise_server_error!
end
alias_method :cleanup!, :reset!
alias_method :reset_session!, :reset!
##
#
# Disconnect from the current driver. A new driver will be instantiated on the next interaction.
#
def quit
@driver.quit if @driver.respond_to? :quit
@document = @driver = nil
@touched = false
@server&.reset_error!
end
##
#
# Raise errors encountered in the server.
#
def raise_server_error!
return unless @server&.error
# Force an explanation for the error being raised as the exception cause
begin
if config.raise_server_errors
raise CapybaraError, 'Your application server raised an error - It has been raised in your test code because Capybara.raise_server_errors == true'
end
rescue CapybaraError => capy_error # rubocop:disable Naming/RescuedExceptionsVariableName
raise @server.error, cause: capy_error
ensure
@server.reset_error!
end
end
##
#
# Returns a hash of response headers. Not supported by all drivers (e.g. Selenium).
#
# @return [Hash<String, String>] A hash of response headers.
#
def response_headers
driver.response_headers
end
##
#
# Returns the current HTTP status code as an integer. Not supported by all drivers (e.g. Selenium).
#
# @return [Integer] Current HTTP status code
#
def status_code
driver.status_code
end
##
#
# @return [String] A snapshot of the DOM of the current document, as it looks right now (potentially modified by JavaScript).
#
def html
driver.html || ''
end
alias_method :body, :html
alias_method :source, :html
##
#
# @return [String] Path of the current page, without any domain information
#
def current_path
# Addressable parsing is more lenient than URI
uri = ::Addressable::URI.parse(current_url)
# Addressable doesn't support opaque URIs - we want nil here
return nil if uri&.scheme == 'about'
path = uri&.path
path unless path&.empty?
end
##
#
# @return [String] Host of the current page
#
def current_host
uri = URI.parse(current_url)
"#{uri.scheme}://#{uri.host}" if uri.host
end
##
#
# @return [String] Fully qualified URL of the current page
#
def current_url
driver.current_url
end
##
#
# Navigate to the given URL. The URL can either be a relative URL or an absolute URL
# The behaviour of either depends on the driver.
#
# session.visit('/foo')
# session.visit('http://google.com')
#
# For drivers which can run against an external application, such as the selenium driver
# giving an absolute URL will navigate to that page. This allows testing applications
# running on remote servers. For these drivers, setting {Capybara.configure app_host} will make the
# remote server the default. For example:
#
# Capybara.app_host = 'http://google.com'
# session.visit('/') # visits the google homepage
#
# If {Capybara.configure always_include_port} is set to `true` and this session is running against
# a rack application, then the port that the rack application is running on will automatically
# be inserted into the URL. Supposing the app is running on port `4567`, doing something like:
#
# visit("http://google.com/test")
#
# Will actually navigate to `http://google.com:4567/test`.
#
# @param [#to_s] visit_uri The URL to navigate to. The parameter will be cast to a String.
#
def visit(visit_uri)
raise_server_error!
@touched = true
visit_uri = ::Addressable::URI.parse(visit_uri.to_s)
base_uri = ::Addressable::URI.parse(config.app_host || server_url)
if base_uri && [nil, 'http', 'https'].include?(visit_uri.scheme)
if visit_uri.relative?
visit_uri_parts = visit_uri.to_hash.compact
# Useful to people deploying to a subdirectory
# and/or single page apps where only the url fragment changes
visit_uri_parts[:path] = base_uri.path + visit_uri.path
visit_uri = base_uri.merge(visit_uri_parts)
end
adjust_server_port(visit_uri)
end
driver.visit(visit_uri.to_s)
end
##
#
# Refresh the page.
#
def refresh
raise_server_error!
driver.refresh
end
##
#
# Move back a single entry in the browser's history.
#
def go_back
driver.go_back
end
##
#
# Move forward a single entry in the browser's history.
#
def go_forward
driver.go_forward
end
##
# @!method send_keys
# @see Capybara::Node::Element#send_keys
#
def send_keys(...)
driver.send_keys(...)
end
##
#
# Returns the element with focus.
#
# Not supported by Rack Test
#
def active_element
Capybara::Queries::ActiveElementQuery.new.resolve_for(self)[0].tap(&:allow_reload!)
end
##
#
# Executes the given block within the context of a node. {#within} takes the
# same options as {Capybara::Node::Finders#find #find}, as well as a block. For the duration of the
# block, any command to Capybara will be handled as though it were scoped
# to the given element.
#
# within(:xpath, './/div[@id="delivery-address"]') do
# fill_in('Street', with: '12 Main Street')
# end
#
# Just as with `#find`, if multiple elements match the selector given to
# {#within}, an error will be raised, and just as with `#find`, this
# behaviour can be controlled through the `:match` and `:exact` options.
#
# It is possible to omit the first parameter, in that case, the selector is
# assumed to be of the type set in {Capybara.configure default_selector}.
#
# within('div#delivery-address') do
# fill_in('Street', with: '12 Main Street')
# end
#
# Note that a lot of uses of {#within} can be replaced more succinctly with
# chaining:
#
# find('div#delivery-address').fill_in('Street', with: '12 Main Street')
#
# @overload within(*find_args)
# @param (see Capybara::Node::Finders#all)
#
# @overload within(a_node)
# @param [Capybara::Node::Base] a_node The node in whose scope the block should be evaluated
#
# @raise [Capybara::ElementNotFound] If the scope can't be found before time expires
#
def within(*args, **kw_args)
new_scope = args.first.respond_to?(:to_capybara_node) ? args.first.to_capybara_node : find(*args, **kw_args)
begin
scopes.push(new_scope)
yield new_scope if block_given?
ensure
scopes.pop
end
end
alias_method :within_element, :within
##
#
# Execute the given block within the a specific fieldset given the id or legend of that fieldset.
#
# @param [String] locator Id or legend of the fieldset
#
def within_fieldset(locator, &block)
within(:fieldset, locator, &block)
end
##
#
# Execute the given block within the a specific table given the id or caption of that table.
#
# @param [String] locator Id or caption of the table
#
def within_table(locator, &block)
within(:table, locator, &block)
end
##
#
# Switch to the given frame.
#
# 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.
# {#within_frame} is preferred over this method and should be used when possible.
# May not be supported by all drivers.
#
# @overload switch_to_frame(element)
# @param [Capybara::Node::Element] element iframe/frame element to switch to
# @overload switch_to_frame(location)
# @param [Symbol] location relative location of the frame to switch to
# * :parent - the parent frame
# * :top - the top level document
#
def switch_to_frame(frame)
case frame
when Capybara::Node::Element
driver.switch_to_frame(frame)
scopes.push(:frame)
when :parent
if scopes.last != :frame
raise Capybara::ScopeError, "`switch_to_frame(:parent)` cannot be called from inside a descendant frame's " \
'`within` block.'
end
scopes.pop
driver.switch_to_frame(:parent)
when :top
idx = scopes.index(:frame)
top_level_scopes = [:frame, nil]
if idx
if scopes.slice(idx..).any? { |scope| !top_level_scopes.include?(scope) }
raise Capybara::ScopeError, "`switch_to_frame(:top)` cannot be called from inside a descendant frame's " \
'`within` block.'
end
scopes.slice!(idx..)
driver.switch_to_frame(:top)
end
else
raise ArgumentError, 'You must provide a frame element, :parent, or :top when calling switch_to_frame'
end
end
##
#
# Execute the given block within the given iframe using given frame, frame name/id or index.
# May not be supported by all drivers.
#
# @overload within_frame(element)
# @param [Capybara::Node::Element] frame element
# @overload within_frame([kind = :frame], locator, **options)
# @param [Symbol] kind Optional selector type (:frame, :css, :xpath, etc.) - Defaults to :frame
# @param [String] locator The locator for the given selector kind. For :frame this is the name/id of a frame/iframe element
# @overload within_frame(index)
# @param [Integer] index index of a frame (0 based)
def within_frame(*args, **kw_args)
switch_to_frame(_find_frame(*args, **kw_args))
begin
yield if block_given?
ensure
switch_to_frame(:parent)
end
end
##
# @return [Capybara::Window] current window
#
def current_window
Window.new(self, driver.current_window_handle)
end
##
# Get all opened windows.
# The order of windows in returned array is not defined.
# The driver may sort windows by their creation time but it's not required.
#
# @return [Array<Capybara::Window>] an array of all windows
#
def windows
driver.window_handles.map do |handle|
Window.new(self, handle)
end
end
##
# Open a new window.
# The current window doesn't change as the result of this call.
# It should be switched to explicitly.
#
# @return [Capybara::Window] window that has been opened
#
def open_new_window(kind = :tab)
window_opened_by do
if driver.method(:open_new_window).arity.zero?
driver.open_new_window
else
driver.open_new_window(kind)
end
end
end
##
# Switch to the given window.
#
# @overload switch_to_window(&block)
# Switches to the first window for which given block returns a value other than false or nil.
# If window that matches block can't be found, the window will be switched back and {Capybara::WindowError} will be raised.
# @example
# window = switch_to_window { title == 'Page title' }
# @raise [Capybara::WindowError] if no window matches given block
# @overload switch_to_window(window)
# @param window [Capybara::Window] window that should be switched to
# @raise [Capybara::Driver::Base#no_such_window_error] if nonexistent (e.g. closed) window was passed
#
# @return [Capybara::Window] window that has been switched to
# @raise [Capybara::ScopeError] if this method is invoked inside {#within} or
# {#within_frame} methods
# @raise [ArgumentError] if both or neither arguments were provided
#
def switch_to_window(window = nil, **options, &window_locator)
raise ArgumentError, '`switch_to_window` can take either a block or a window, not both' if window && window_locator
raise ArgumentError, '`switch_to_window`: either window or block should be provided' if !window && !window_locator
unless scopes.last.nil?
raise Capybara::ScopeError, '`switch_to_window` is not supposed to be invoked from ' \
'`within` or `within_frame` blocks.'
end
_switch_to_window(window, **options, &window_locator)
end
##
# This method does the following:
#
# 1. Switches to the given window (it can be located by window instance/lambda/string).
# 2. Executes the given block (within window located at previous step).
# 3. Switches back (this step will be invoked even if an exception occurs at the second step).
#
# @overload within_window(window) { do_something }
# @param window [Capybara::Window] instance of {Capybara::Window} class
# that will be switched to
# @raise [driver#no_such_window_error] if nonexistent (e.g. closed) window was passed
# @overload within_window(proc_or_lambda) { do_something }
# @param lambda [Proc] First window for which lambda
# returns a value other than false or nil will be switched to.
# @example
# within_window(->{ page.title == 'Page title' }) { click_button 'Submit' }
# @raise [Capybara::WindowError] if no window matching lambda was found
#
# @raise [Capybara::ScopeError] if this method is invoked inside {#within_frame} method
# @return value returned by the block
#
def within_window(window_or_proc)
original = current_window
scopes << nil
begin
case window_or_proc
when Capybara::Window
_switch_to_window(window_or_proc) unless original == window_or_proc
when Proc
_switch_to_window { window_or_proc.call }
else
raise ArgumentError, '`#within_window` requires a `Capybara::Window` instance or a lambda'
end
begin
yield if block_given?
ensure
_switch_to_window(original) unless original == window_or_proc
end
ensure
scopes.pop
end
end
##
# Get the window that has been opened by the passed block.
# It will wait for it to be opened (in the same way as other Capybara methods wait).
# It's better to use this method than `windows.last`
# {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}.
#
# @overload window_opened_by(**options, &block)
# @param options [Hash]
# @option options [Numeric] :wait maximum wait time. Defaults to {Capybara.configure default_max_wait_time}
# @return [Capybara::Window] the window that has been opened within a block
# @raise [Capybara::WindowError] if block passed to window hasn't opened window
# or opened more than one window
#
def window_opened_by(**options)
old_handles = driver.window_handles
yield
synchronize_windows(options) do
opened_handles = (driver.window_handles - old_handles)
if opened_handles.size != 1
raise Capybara::WindowError, 'block passed to #window_opened_by ' \
"opened #{opened_handles.size} windows instead of 1"
end
Window.new(self, opened_handles.first)
end
end
##
#
# Execute the given script, not returning a result. This is useful for scripts that return
# complex objects, such as jQuery statements. {#execute_script} should be used over
# {#evaluate_script} whenever possible.
#
# @param [String] script A string of JavaScript to execute
# @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 drivers
#
def execute_script(script, *args)
@touched = true
driver.execute_script(script, *driver_args(args))
end
##
#
# Evaluate the given JavaScript and return the result. Be careful when using this with
# scripts that return complex objects, such as jQuery statements. {#execute_script} might
# be a better alternative.
#
# @param [String] script A string of JavaScript to evaluate
# @param args Optional arguments that will be passed to the script
# @return [Object] The result of the evaluated JavaScript (may be driver specific)
#
def evaluate_script(script, *args)
@touched = true
result = driver.evaluate_script(script.strip, *driver_args(args))
element_script_result(result)
end
##
#
# Evaluate the given JavaScript and obtain the result from a callback function which will be passed as the last argument to the script.
#
# @param [String] script A string of JavaScript to evaluate
# @param args Optional arguments that will be passed to the script
# @return [Object] The result of the evaluated JavaScript (may be driver specific)
#
def evaluate_async_script(script, *args)
@touched = true
result = driver.evaluate_async_script(script, *driver_args(args))
element_script_result(result)
end
##
#
# Execute the block, accepting a alert.
#
# @!macro modal_params
# Expects a block whose actions will trigger the display modal to appear.
# @example
# $0 do
# click_link('link that triggers appearance of system modal')
# end
# @overload $0(text, **options, &blk)
# @param text [String, Regexp] Text or regex to match against the text in the modal. If not provided any modal is matched.
# @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}.
# @yield Block whose actions will trigger the system modal
# @overload $0(**options, &blk)
# @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}.
# @yield Block whose actions will trigger the system modal
# @return [String] the message shown in the modal
# @raise [Capybara::ModalNotFound] if modal dialog hasn't been found
#
def accept_alert(text = nil, **options, &blk)
accept_modal(:alert, text, options, &blk)
end
##
#
# Execute the block, accepting a confirm.
#
# @macro modal_params
#
def accept_confirm(text = nil, **options, &blk)
accept_modal(:confirm, text, options, &blk)
end
##
#
# Execute the block, dismissing a confirm.
#
# @macro modal_params
#
def dismiss_confirm(text = nil, **options, &blk)
dismiss_modal(:confirm, text, options, &blk)
end
##
#
# Execute the block, accepting a prompt, optionally responding to the prompt.
#
# @macro modal_params
# @option options [String] :with Response to provide to the prompt
#
def accept_prompt(text = nil, **options, &blk)
accept_modal(:prompt, text, options, &blk)
end
##
#
# Execute the block, dismissing a prompt.
#
# @macro modal_params
#
def dismiss_prompt(text = nil, **options, &blk)
dismiss_modal(:prompt, text, options, &blk)
end
##
#
# Save a snapshot of the page. If {Capybara.configure asset_host} is set it will inject `base` tag
# pointing to {Capybara.configure asset_host}.
#
# If invoked without arguments it will save file to {Capybara.configure save_path}
# and file will be given randomly generated filename. If invoked with a relative path
# the path will be relative to {Capybara.configure save_path}.
#
# @param [String] path the path to where it should be saved
# @return [String] the path to which the file was saved
#
def save_page(path = nil)
prepare_path(path, 'html').tap do |p_path|
File.write(p_path, Capybara::Helpers.inject_asset_host(body, host: config.asset_host), mode: 'wb')
end
end
##
#
# Save a snapshot of the page and open it in a browser for inspection.
#
# If invoked without arguments it will save file to {Capybara.configure save_path}
# and file will be given randomly generated filename. If invoked with a relative path
# the path will be relative to {Capybara.configure save_path}.
#
# @param [String] path the path to where it should be saved
#
def save_and_open_page(path = nil)
save_page(path).tap { |s_path| open_file(s_path) }
end
##
#
# Save a screenshot of page.
#
# If invoked without arguments it will save file to {Capybara.configure save_path}
# and file will be given randomly generated filename. If invoked with a relative path
# the path will be relative to {Capybara.configure save_path}.
#
# @param [String] path the path to where it should be saved
# @param [Hash] options a customizable set of options
# @return [String] the path to which the file was saved
def save_screenshot(path = nil, **options)
prepare_path(path, 'png').tap { |p_path| driver.save_screenshot(p_path, **options) }
end
##
#
# Save a screenshot of the page and open it for inspection.
#
# If invoked without arguments it will save file to {Capybara.configure save_path}
# and file will be given randomly generated filename. If invoked with a relative path
# the path will be relative to {Capybara.configure save_path}.
#
# @param [String] path the path to where it should be saved
# @param [Hash] options a customizable set of options
#
def save_and_open_screenshot(path = nil, **options)
save_screenshot(path, **options).tap { |s_path| open_file(s_path) }
end
def document
@document ||= Capybara::Node::Document.new(self, driver)
end
NODE_METHODS.each do |method|
class_eval <<~METHOD, __FILE__, __LINE__ + 1
def #{method}(...)
@touched = true
current_scope.#{method}(...)
end
METHOD
end
DOCUMENT_METHODS.each do |method|
class_eval <<~METHOD, __FILE__, __LINE__ + 1
def #{method}(...)
document.#{method}(...)
end
METHOD
end
def inspect
%(#<Capybara::Session>)
end
def current_scope
scope = scopes.last
[nil, :frame].include?(scope) ? document : scope
end
##
#
# Yield a block using a specific maximum wait time.
#
def using_wait_time(seconds, &block)
if Capybara.threadsafe
begin
previous_wait_time = config.default_max_wait_time
config.default_max_wait_time = seconds
yield
ensure
config.default_max_wait_time = previous_wait_time
end
else
Capybara.using_wait_time(seconds, &block)
end
end
##
#
# Accepts a block to set the configuration options if {Capybara.configure threadsafe} is `true`. Note that some options only have an effect
# if set at initialization time, so look at the configuration block that can be passed to the initializer too.
#
def configure
raise 'Session configuration is only supported when Capybara.threadsafe == true' unless Capybara.threadsafe
yield config
end
def self.instance_created?
@@instance_created
end
def config
@config ||= if Capybara.threadsafe
Capybara.session_options.dup
else
Capybara::ReadOnlySessionConfig.new(Capybara.session_options)
end
end
def server_url
@server&.base_url
end
private
@@instance_created = false # rubocop:disable Style/ClassVars
def driver_args(args)
args.map { |arg| arg.is_a?(Capybara::Node::Element) ? arg.base : arg }
end
def accept_modal(type, text_or_options, options, &blk)
driver.accept_modal(type, **modal_options(text_or_options, **options), &blk)
end
def dismiss_modal(type, text_or_options, options, &blk)
driver.dismiss_modal(type, **modal_options(text_or_options, **options), &blk)
end
def modal_options(text = nil, **options)
options[:text] ||= text unless text.nil?
options[:wait] ||= config.default_max_wait_time
options
end
def open_file(path)
require 'launchy'
Launchy.open(path)
rescue LoadError
warn "File saved to #{path}.\nPlease install the launchy gem to open the file automatically."
end
def prepare_path(path, extension)
File.expand_path(path || default_fn(extension), config.save_path).tap do |p_path|
FileUtils.mkdir_p(File.dirname(p_path))
end
end
def default_fn(extension)
timestamp = Time.new.strftime('%Y%m%d%H%M%S')
"capybara-#{timestamp}#{rand(10**10)}.#{extension}"
end
def scopes
@scopes ||= [nil]
end
def element_script_result(arg)
case arg
when Array
arg.map { |subarg| element_script_result(subarg) }
when Hash
arg.transform_values! { |value| element_script_result(value) }
when Capybara::Driver::Node
Capybara::Node::Element.new(self, arg, nil, nil)
else
arg
end
end
def adjust_server_port(uri)
uri.port ||= @server.port if @server && config.always_include_port
end
def _find_frame(*args, **kw_args)
case args[0]
when Capybara::Node::Element
args[0]
when String, nil
find(:frame, *args, **kw_args)
when Symbol
find(*args, **kw_args)
when Integer
idx = args[0]
all(:frame, minimum: idx + 1)[idx]
else
raise TypeError
end
end
def _switch_to_window(window = nil, **options, &window_locator)
raise Capybara::ScopeError, 'Window cannot be switched inside a `within_frame` block' if scopes.include?(:frame)
raise Capybara::ScopeError, 'Window cannot be switched inside a `within` block' unless scopes.last.nil?
if window
driver.switch_to_window(window.handle)
window
else
synchronize_windows(options) do
original_window_handle = driver.current_window_handle
begin
_switch_to_window_by_locator(&window_locator)
rescue StandardError
driver.switch_to_window(original_window_handle)
raise
end
end
end
end
def _switch_to_window_by_locator
driver.window_handles.each do |handle|
| ruby | MIT | b3325b198464b806f07ec2011ceb532d6d5cf4ab | 2026-01-04T15:38:10.098638Z | true |
teamcapybara/capybara | https://github.com/teamcapybara/capybara/blob/b3325b198464b806f07ec2011ceb532d6d5cf4ab/lib/capybara/version.rb | lib/capybara/version.rb | # frozen_string_literal: true
module Capybara
VERSION = '3.40.0'
end
| ruby | MIT | b3325b198464b806f07ec2011ceb532d6d5cf4ab | 2026-01-04T15:38:10.098638Z | false |
teamcapybara/capybara | https://github.com/teamcapybara/capybara/blob/b3325b198464b806f07ec2011ceb532d6d5cf4ab/lib/capybara/rails.rb | lib/capybara/rails.rb | # frozen_string_literal: true
require 'capybara/dsl'
Capybara.app = Rack::Builder.new do
map '/' do
run Rails.application
end
end.to_app
Capybara.save_path = Rails.root.join('tmp/capybara')
# Override default rack_test driver to respect data-method attributes.
Capybara.register_driver :rack_test do |app|
Capybara::RackTest::Driver.new(app, respect_data_method: true)
end
| ruby | MIT | b3325b198464b806f07ec2011ceb532d6d5cf4ab | 2026-01-04T15:38:10.098638Z | false |
teamcapybara/capybara | https://github.com/teamcapybara/capybara/blob/b3325b198464b806f07ec2011ceb532d6d5cf4ab/lib/capybara/window.rb | lib/capybara/window.rb | # frozen_string_literal: true
module Capybara
##
# The {Window} class represents a browser window.
#
# You can get an instance of the class by calling any of:
#
# * {Capybara::Session#windows}
# * {Capybara::Session#current_window}
# * {Capybara::Session#window_opened_by}
# * {Capybara::Session#switch_to_window}
#
# Note that some drivers (e.g. Selenium) support getting size of/resizing/closing only
# current window. So if you invoke such method for:
#
# * window that is current, Capybara will make 2 Selenium method invocations
# (get handle of current window + get size/resize/close).
# * window that is not current, Capybara will make 4 Selenium method invocations
# (get handle of current window + switch to given handle + get size/resize/close + switch to original handle)
#
class Window
# @return [String] a string that uniquely identifies window within session
attr_reader :handle
# @return [Capybara::Session] session that this window belongs to
attr_reader :session
# @api private
def initialize(session, handle)
@session = session
@driver = session.driver
@handle = handle
end
##
# @return [Boolean] whether the window is not closed
def exists?
@driver.window_handles.include?(@handle)
end
##
# @return [Boolean] whether the window is closed
def closed?
!exists?
end
##
# @return [Boolean] whether this window is the window in which commands are being executed
def current?
@driver.current_window_handle == @handle
rescue @driver.no_such_window_error
false
end
##
# Close window.
#
# If this method was called for window that is current, then after calling this method
# future invocations of other Capybara methods should raise
# {Capybara::Driver::Base#no_such_window_error session.driver.no_such_window_error} until another window will be switched to.
#
# @!macro about_current
# If this method was called for window that is not current, then after calling this method
# current window should remain the same as it was before calling this method.
#
def close
@driver.close_window(handle)
end
##
# Get window size.
#
# @macro about_current
# @return [Array<(Integer, Integer)>] an array with width and height
#
def size
@driver.window_size(handle)
end
##
# Resize window.
#
# @macro about_current
# @param width [Integer] the new window width in pixels
# @param height [Integer] the new window height in pixels
#
def resize_to(width, height)
wait_for_stable_size { @driver.resize_window_to(handle, width, height) }
end
##
# Maximize window.
#
# If a particular driver (e.g. headless driver) doesn't have concept of maximizing it
# may not support this method.
#
# @macro about_current
#
def maximize
wait_for_stable_size { @driver.maximize_window(handle) }
end
##
# Fullscreen window.
#
# If a particular driver doesn't have concept of fullscreen it may not support this method.
#
# @macro about_current
#
def fullscreen
@driver.fullscreen_window(handle)
end
def eql?(other)
other.is_a?(self.class) && @session == other.session && @handle == other.handle
end
alias_method :==, :eql?
def hash
[@session, @handle].hash
end
def inspect
"#<Window @handle=#{@handle.inspect}>"
end
private
def wait_for_stable_size(seconds = session.config.default_max_wait_time)
res = yield if block_given?
timer = Capybara::Helpers.timer(expire_in: seconds)
loop do
prev_size = size
sleep 0.025
return res if prev_size == size
break if timer.expired?
end
raise Capybara::WindowError, "Window size not stable within #{seconds} seconds."
end
end
end
| ruby | MIT | b3325b198464b806f07ec2011ceb532d6d5cf4ab | 2026-01-04T15:38:10.098638Z | false |
teamcapybara/capybara | https://github.com/teamcapybara/capybara/blob/b3325b198464b806f07ec2011ceb532d6d5cf4ab/lib/capybara/result.rb | lib/capybara/result.rb | # frozen_string_literal: true
require 'forwardable'
module Capybara
##
# A {Capybara::Result} represents a collection of {Capybara::Node::Element} on the page. It is possible to interact with this
# collection similar to an Array because it implements Enumerable and offers the following Array methods through delegation:
#
# * \[\]
# * each()
# * at()
# * size()
# * count()
# * length()
# * first()
# * last()
# * empty?()
# * values_at()
# * sample()
#
# @see Capybara::Node::Element
#
class Result
include Enumerable
extend Forwardable
def initialize(elements, query)
@elements = elements
@result_cache = []
@filter_errors = []
@results_enum = lazy_select_elements { |node| query.matches_filters?(node, @filter_errors) }
@query = query
@allow_reload = false
end
def_delegators :full_results, :size, :length, :last, :values_at, :inspect, :sample, :to_ary
alias index find_index
def each(&block)
return enum_for(:each) unless block
@result_cache.each(&block)
loop do
next_result = @results_enum.next
add_to_cache(next_result)
yield next_result
end
self
end
def [](*args)
idx, length = args
max_idx = case idx
when Integer
if idx.negative?
nil
else
length.nil? ? idx : idx + length - 1
end
when Range
# idx.max is broken with beginless ranges
# idx.end && idx.max # endless range will have end == nil
max = idx.end
max = nil if max&.negative?
max -= 1 if max && idx.exclude_end?
max
end
if max_idx.nil?
full_results[*args]
else
load_up_to(max_idx + 1)
@result_cache[*args]
end
end
alias :at :[]
def empty?
!any?
end
def compare_count
return 0 unless @query
count, min, max, between = @query.options.values_at(:count, :minimum, :maximum, :between)
# Only check filters for as many elements as necessary to determine result
if count && (count = Integer(count))
return load_up_to(count + 1) <=> count
end
return -1 if min && (min = Integer(min)) && (load_up_to(min) < min)
return 1 if max && (max = Integer(max)) && (load_up_to(max + 1) > max)
if between
min, max = (between.begin && between.min) || 1, between.end
max -= 1 if max && between.exclude_end?
size = load_up_to(max ? max + 1 : min)
return size <=> min unless between.include?(size)
end
0
end
def matches_count?
compare_count.zero?
end
def failure_message
message = @query.failure_message
if count.zero?
message << ' but there were no matches'
else
message << ", found #{count} #{Capybara::Helpers.declension('match', 'matches', count)}: " \
<< full_results.map { |r| r.text.inspect }.join(', ')
end
unless rest.empty?
elements = rest.map { |el| el.text rescue '<<ERROR>>' }.map(&:inspect).join(', ') # rubocop:disable Style/RescueModifier
message << '. Also found ' << elements << ', which matched the selector but not all filters. '
message << @filter_errors.join('. ') if (rest.size == 1) && count.zero?
end
message
end
def negative_failure_message
failure_message.sub(/(to find)/, 'not \1')
end
def unfiltered_size
@elements.length
end
##
# @api private
#
def allow_reload!
@allow_reload = true
self
end
private
def add_to_cache(elem)
elem.allow_reload!(@result_cache.size) if @allow_reload
@result_cache << elem
end
def load_up_to(num)
loop do
break if @result_cache.size >= num
add_to_cache(@results_enum.next)
end
@result_cache.size
end
def full_results
loop { @result_cache << @results_enum.next }
@result_cache
end
def rest
@rest ||= @elements - full_results
end
if RUBY_PLATFORM == 'java'
# JRuby < 9.2.8.0 has an issue with lazy enumerators which
# causes a concurrency issue with network requests here
# https://github.com/jruby/jruby/issues/4212
# while JRuby >= 9.2.8.0 leaks threads when using lazy enumerators
# https://github.com/teamcapybara/capybara/issues/2349
# so disable the use and JRuby users will need to pay a performance penalty
def lazy_select_elements(&block)
@elements.select(&block).to_enum # non-lazy evaluation
end
else
def lazy_select_elements(&block)
@elements.lazy.select(&block)
end
end
end
end
| ruby | MIT | b3325b198464b806f07ec2011ceb532d6d5cf4ab | 2026-01-04T15:38:10.098638Z | false |
teamcapybara/capybara | https://github.com/teamcapybara/capybara/blob/b3325b198464b806f07ec2011ceb532d6d5cf4ab/lib/capybara/helpers.rb | lib/capybara/helpers.rb | # frozen_string_literal: true
module Capybara
# @api private
module Helpers
module_function
##
# @deprecated
# Normalizes whitespace space by stripping leading and trailing
# whitespace and replacing sequences of whitespace characters
# with a single space.
#
# @param [String] text Text to normalize
# @return [String] Normalized text
#
def normalize_whitespace(text)
Capybara::Helpers.warn 'DEPRECATED: Capybara::Helpers::normalize_whitespace is deprecated, please update your driver'
text.to_s.gsub(/[[:space:]]+/, ' ').strip
end
##
#
# Escapes any characters that would have special meaning in a regexp
# if text is not a regexp
#
# @param [String] text Text to escape
# @param [Boolean] exact (false) Whether or not this should be an exact text match
# @param [Fixnum, Boolean, nil] options Options passed to Regexp.new when creating the Regexp
# @return [Regexp] Regexp to match the passed in text and options
#
def to_regexp(text, exact: false, all_whitespace: false, options: nil)
return text if text.is_a?(Regexp)
escaped = Regexp.escape(text)
escaped = escaped.gsub('\\ ', '[[:blank:]]') if all_whitespace
escaped = "\\A#{escaped}\\z" if exact
Regexp.new(escaped, options)
end
##
#
# Injects a `<base>` tag into the given HTML code, pointing to
# {Capybara.configure asset_host}.
#
# @param [String] html HTML code to inject into
# @param [URL] host (Capybara.asset_host) The host from which assets should be loaded
# @return [String] The modified HTML code
#
def inject_asset_host(html, host: Capybara.asset_host)
if host && Nokogiri::HTML(html).css('base').empty?
html.match(/<head[^<]*?>/) do |m|
return html.clone.insert m.end(0), "<base href='#{host}' />"
end
end
html
end
##
#
# A poor man's `pluralize`. Given two declensions, one singular and one
# plural, as well as a count, this will pick the correct declension. This
# way we can generate grammatically correct error message.
#
# @param [String] singular The singular form of the word
# @param [String] plural The plural form of the word
# @param [Integer] count The number of items
#
def declension(singular, plural, count)
count == 1 ? singular : plural
end
def filter_backtrace(trace)
return 'No backtrace' unless trace
filter = %r{lib/capybara/|lib/rspec/|lib/minitest/|delegate.rb}
new_trace = trace.take_while { |line| line !~ filter }
new_trace = trace.grep_v(filter) if new_trace.empty?
new_trace = trace.dup if new_trace.empty?
new_trace.first.split(':in ', 2).first
end
def warn(message, uplevel: 1)
Kernel.warn(message, uplevel: uplevel)
end
if defined?(Process::CLOCK_MONOTONIC_RAW)
def monotonic_time; Process.clock_gettime Process::CLOCK_MONOTONIC_RAW; end
elsif defined?(Process::CLOCK_MONOTONIC_PRECISE)
def monotonic_time; Process.clock_gettime Process::CLOCK_MONOTONIC_PRECISE; end
elsif defined?(Process::CLOCK_MONOTONIC)
def monotonic_time; Process.clock_gettime Process::CLOCK_MONOTONIC; end
else
def monotonic_time; Time.now.to_f; end
end
def timer(expire_in:)
Timer.new(expire_in)
end
class Timer
def initialize(expire_in)
@start = current
@expire_in = expire_in
end
def expired?
if stalled?
raise Capybara::FrozenInTime, 'Time appears to be frozen. Capybara does not work with libraries which freeze time, consider using time travelling instead'
end
current - @start >= @expire_in
end
def stalled?
@start == current
end
private
def current
Capybara::Helpers.monotonic_time
end
end
end
end
| ruby | MIT | b3325b198464b806f07ec2011ceb532d6d5cf4ab | 2026-01-04T15:38:10.098638Z | false |
teamcapybara/capybara | https://github.com/teamcapybara/capybara/blob/b3325b198464b806f07ec2011ceb532d6d5cf4ab/lib/capybara/dsl.rb | lib/capybara/dsl.rb | # frozen_string_literal: true
require 'capybara'
module Capybara
module DSL
def self.included(base)
warn 'including Capybara::DSL in the global scope is not recommended!' if base == Object
super
end
def self.extended(base)
warn 'extending the main object with Capybara::DSL is not recommended!' if base == TOPLEVEL_BINDING.eval('self')
super
end
##
#
# Shortcut to working in a different session.
#
def using_session(name_or_session, &block)
Capybara.using_session(name_or_session, &block)
end
# Shortcut to using a different wait time.
#
def using_wait_time(seconds, &block)
page.using_wait_time(seconds, &block)
end
##
#
# Shortcut to accessing the current session.
#
# class MyClass
# include Capybara::DSL
#
# def has_header?
# page.has_css?('h1')
# end
# end
#
# @return [Capybara::Session] The current session object
#
def page
Capybara.current_session
end
Session::DSL_METHODS.each do |method|
class_eval <<~METHOD, __FILE__, __LINE__ + 1
def #{method}(...)
page.method("#{method}").call(...)
end
METHOD
end
end
extend(Capybara::DSL)
end
| ruby | MIT | b3325b198464b806f07ec2011ceb532d6d5cf4ab | 2026-01-04T15:38:10.098638Z | false |
teamcapybara/capybara | https://github.com/teamcapybara/capybara/blob/b3325b198464b806f07ec2011ceb532d6d5cf4ab/lib/capybara/minitest.rb | lib/capybara/minitest.rb | # frozen_string_literal: true
require 'minitest'
require 'capybara/dsl'
module Capybara
module Minitest
module Assertions
##
# Assert text exists
#
# @!method assert_content
# @!method assert_text
# See {Capybara::Node::Matchers#assert_text}
##
# Assert text does not exist
#
# @!method refute_content
# @!method assert_no_content
# @!method refute_text
# @!method assert_no_text
# See {Capybara::Node::Matchers#assert_no_text}
##
# Assertion that page title does match
#
# @!method assert_title
# See {Capybara::Node::DocumentMatchers#assert_title}
##
# Assertion that page title does not match
#
# @!method refute_title
# @!method assert_no_title
# See {Capybara::Node::DocumentMatchers#assert_no_title}
##
# Assertion that current path matches
#
# @!method assert_current_path
# See {Capybara::SessionMatchers#assert_current_path}
##
# Assertion that current page does not match
#
# @!method refute_current_path
# @!method assert_no_current_path
# See {Capybara::SessionMatchers#assert_no_current_path}
%w[text no_text title no_title current_path no_current_path].each do |assertion_name|
class_eval <<-ASSERTION, __FILE__, __LINE__ + 1
def assert_#{assertion_name}(*args, **kwargs, &optional_filter_block)
self.assertions +=1
subject, args = determine_subject(args)
subject.assert_#{assertion_name}(*args, **kwargs, &optional_filter_block)
rescue Capybara::ExpectationNotMet => e
raise ::Minitest::Assertion, e.message
end
ASSERTION
end
alias_method :refute_title, :assert_no_title
alias_method :refute_text, :assert_no_text
alias_method :refute_content, :refute_text
alias_method :refute_current_path, :assert_no_current_path
alias_method :assert_content, :assert_text
alias_method :assert_no_content, :refute_text
##
# Assert selector exists on page
#
# @!method assert_selector
# See {Capybara::Node::Matchers#assert_selector}
##
# Assert selector does not exist on page
#
# @!method refute_selector
# @!method assert_no_selector
# See {Capybara::Node::Matchers#assert_no_selector}
##
# Assert element matches selector
#
# @!method assert_matches_selector
# See {Capybara::Node::Matchers#assert_matches_selector}
##
# Assert element does not match selector
#
# @!method refute_matches_selector
# @!method assert_not_matches_selector
# See {Capybara::Node::Matchers#assert_not_matches_selector}
##
# Assert all of the provided selectors exist on page
#
# @!method assert_all_of_selectors
# See {Capybara::Node::Matchers#assert_all_of_selectors}
##
# Assert none of the provided selectors exist on page
#
# @!method assert_none_of_selectors
# See {Capybara::Node::Matchers#assert_none_of_selectors}
##
# Assert any of the provided selectors exist on page
#
# @!method assert_any_of_selectors
# See {Capybara::Node::Matchers#assert_any_of_selectors}
##
# Assert element has the provided CSS styles
#
# @!method assert_matches_style
# See {Capybara::Node::Matchers#assert_matches_style}
##
# Assert element has a matching sibling
#
# @!method assert_sibling
# See {Capybara::Node::Matchers#assert_sibling}
##
# Assert element does not have a matching sibling
#
# @!method refute_sibling
# @!method assert_no_sibling
# See {Capybara::Node::Matchers#assert_no_sibling}
##
# Assert element has a matching ancestor
#
# @!method assert_ancestor
# See {Capybara::Node::Matchers#assert_ancestor}
##
# Assert element does not have a matching ancestor
#
# @!method refute_ancestor
# @!method assert_no_ancestor
# See {Capybara::Node::Matchers#assert_no_ancestor}
%w[selector no_selector matches_style
all_of_selectors none_of_selectors any_of_selectors
matches_selector not_matches_selector
sibling no_sibling ancestor no_ancestor].each do |assertion_name|
class_eval <<-ASSERTION, __FILE__, __LINE__ + 1
def assert_#{assertion_name} *args, &optional_filter_block
self.assertions +=1
subject, args = determine_subject(args)
subject.assert_#{assertion_name}(*args, &optional_filter_block)
rescue Capybara::ExpectationNotMet => e
raise ::Minitest::Assertion, e.message
end
ASSERTION
ruby2_keywords "assert_#{assertion_name}" if respond_to?(:ruby2_keywords)
end
alias_method :refute_selector, :assert_no_selector
alias_method :refute_matches_selector, :assert_not_matches_selector
alias_method :refute_ancestor, :assert_no_ancestor
alias_method :refute_sibling, :assert_no_sibling
##
# Assert that provided xpath exists
#
# @!method assert_xpath
# See {Capybara::Node::Matchers#has_xpath?}
##
# Assert that provide xpath does not exist
#
# @!method refute_xpath
# @!method assert_no_xpath
# See {Capybara::Node::Matchers#has_no_xpath?}
##
# Assert that provided css exists
#
# @!method assert_css
# See {Capybara::Node::Matchers#has_css?}
##
# Assert that provided css does not exist
#
# @!method refute_css
# @!method assert_no_css
# See {Capybara::Node::Matchers#has_no_css?}
##
# Assert that provided element exists
#
# @!method assert_element
# See {Capybara::Node::Matchers#has_element?}
##
# Assert that provided element does not exist
#
# @!method assert_no_element
# @!method refute_element
# See {Capybara::Node::Matchers#has_no_element?}
##
# Assert that provided link exists
#
# @!method assert_link
# See {Capybara::Node::Matchers#has_link?}
##
# Assert that provided link does not exist
#
# @!method assert_no_link
# @!method refute_link
# See {Capybara::Node::Matchers#has_no_link?}
##
# Assert that provided button exists
#
# @!method assert_button
# See {Capybara::Node::Matchers#has_button?}
##
# Assert that provided button does not exist
#
# @!method refute_button
# @!method assert_no_button
# See {Capybara::Node::Matchers#has_no_button?}
##
# Assert that provided field exists
#
# @!method assert_field
# See {Capybara::Node::Matchers#has_field?}
##
# Assert that provided field does not exist
#
# @!method refute_field
# @!method assert_no_field
# See {Capybara::Node::Matchers#has_no_field?}
##
# Assert that provided checked field exists
#
# @!method assert_checked_field
# See {Capybara::Node::Matchers#has_checked_field?}
##
# Assert that provided checked_field does not exist
#
# @!method assert_no_checked_field
# @!method refute_checked_field
# See {Capybara::Node::Matchers#has_no_checked_field?}
##
# Assert that provided unchecked field exists
#
# @!method assert_unchecked_field
# See {Capybara::Node::Matchers#has_unchecked_field?}
##
# Assert that provided unchecked field does not exist
#
# @!method assert_no_unchecked_field
# @!method refute_unchecked_field
# See {Capybara::Node::Matchers#has_no_unchecked_field?}
##
# Assert that provided select exists
#
# @!method assert_select
# See {Capybara::Node::Matchers#has_select?}
##
# Assert that provided select does not exist
#
# @!method refute_select
# @!method assert_no_select
# See {Capybara::Node::Matchers#has_no_select?}
##
# Assert that provided table exists
#
# @!method assert_table
# See {Capybara::Node::Matchers#has_table?}
##
# Assert that provided table does not exist
#
# @!method refute_table
# @!method assert_no_table
# See {Capybara::Node::Matchers#has_no_table?}
%w[xpath css element link button field select table].each do |selector_type|
define_method "assert_#{selector_type}" do |*args, &optional_filter_block|
subject, args = determine_subject(args)
locator, options = extract_locator(args)
assert_selector(subject, selector_type.to_sym, locator, **options, &optional_filter_block)
end
ruby2_keywords "assert_#{selector_type}" if respond_to?(:ruby2_keywords)
define_method "assert_no_#{selector_type}" do |*args, &optional_filter_block|
subject, args = determine_subject(args)
locator, options = extract_locator(args)
assert_no_selector(subject, selector_type.to_sym, locator, **options, &optional_filter_block)
end
ruby2_keywords "assert_no_#{selector_type}" if respond_to?(:ruby2_keywords)
alias_method "refute_#{selector_type}", "assert_no_#{selector_type}"
end
%w[checked unchecked].each do |field_type|
define_method "assert_#{field_type}_field" do |*args, &optional_filter_block|
subject, args = determine_subject(args)
locator, options = extract_locator(args)
assert_selector(subject, :field, locator, **options.merge(field_type.to_sym => true), &optional_filter_block)
end
ruby2_keywords "assert_#{field_type}_field" if respond_to?(:ruby2_keywords)
define_method "assert_no_#{field_type}_field" do |*args, &optional_filter_block|
subject, args = determine_subject(args)
locator, options = extract_locator(args)
assert_no_selector(
subject,
:field,
locator,
**options.merge(field_type.to_sym => true),
&optional_filter_block
)
end
ruby2_keywords "assert_no_#{field_type}_field" if respond_to?(:ruby2_keywords)
alias_method "refute_#{field_type}_field", "assert_no_#{field_type}_field"
end
##
# Assert that element matches xpath
#
# @!method assert_matches_xpath
# See {Capybara::Node::Matchers#matches_xpath?}
##
# Assert that element does not match xpath
#
# @!method refute_matches_xpath
# @!method assert_not_matches_xpath
# See {Capybara::Node::Matchers#not_matches_xpath?}
##
# Assert that element matches css
#
# @!method assert_matches_css
# See {Capybara::Node::Matchers#matches_css?}
##
# Assert that element matches css
#
# @!method refute_matches_css
# @!method assert_not_matches_css
# See {Capybara::Node::Matchers#not_matches_css?}
%w[xpath css].each do |selector_type|
define_method "assert_matches_#{selector_type}" do |*args, &optional_filter_block|
subject, args = determine_subject(args)
assert_matches_selector(subject, selector_type.to_sym, *args, &optional_filter_block)
end
ruby2_keywords "assert_matches_#{selector_type}" if respond_to?(:ruby2_keywords)
define_method "assert_not_matches_#{selector_type}" do |*args, &optional_filter_block|
subject, args = determine_subject(args)
assert_not_matches_selector(subject, selector_type.to_sym, *args, &optional_filter_block)
end
ruby2_keywords "assert_not_matches_#{selector_type}" if respond_to?(:ruby2_keywords)
alias_method "refute_matches_#{selector_type}", "assert_not_matches_#{selector_type}"
end
private
def determine_subject(args)
case args.first
when Capybara::Session, Capybara::Node::Base, Capybara::Node::Simple
[args.shift, args]
when ->(arg) { arg.respond_to?(:to_capybara_node) }
[args.shift.to_capybara_node, args]
else
[page, args]
end
end
def extract_locator(args)
locator, options = *args, {}
locator, options = nil, locator if locator.is_a? Hash
[locator, options]
end
end
end
end
| ruby | MIT | b3325b198464b806f07ec2011ceb532d6d5cf4ab | 2026-01-04T15:38:10.098638Z | false |
teamcapybara/capybara | https://github.com/teamcapybara/capybara/blob/b3325b198464b806f07ec2011ceb532d6d5cf4ab/lib/capybara/registration_container.rb | lib/capybara/registration_container.rb | # frozen_string_literal: true
module Capybara
# @api private
class RegistrationContainer
def names
@registered.keys
end
def [](name)
@registered[name]
end
def []=(name, value)
Capybara::Helpers.warn 'DEPRECATED: Directly setting drivers/servers is deprecated, please use Capybara.register_driver/register_server instead'
@registered[name] = value
end
def method_missing(method_name, ...)
if @registered.respond_to?(method_name)
Capybara::Helpers.warn "DEPRECATED: Calling '#{method_name}' on the drivers/servers container is deprecated without replacement"
return @registered.public_send(method_name, ...)
end
super
end
def respond_to_missing?(method_name, include_all)
@registered.respond_to?(method_name) || super
end
private
def initialize
@registered = {}
end
def register(name, block)
@registered[name] = block
end
end
end
| ruby | MIT | b3325b198464b806f07ec2011ceb532d6d5cf4ab | 2026-01-04T15:38:10.098638Z | false |
teamcapybara/capybara | https://github.com/teamcapybara/capybara/blob/b3325b198464b806f07ec2011ceb532d6d5cf4ab/lib/capybara/config.rb | lib/capybara/config.rb | # frozen_string_literal: true
require 'forwardable'
require 'capybara/session/config'
module Capybara
class Config
extend Forwardable
OPTIONS = %i[
app reuse_server threadsafe server default_driver javascript_driver use_html5_parsing allow_gumbo
].freeze
attr_accessor :app, :use_html5_parsing
attr_reader :reuse_server, :threadsafe, :session_options # rubocop:disable Style/BisectedAttrAccessor
attr_writer :default_driver, :javascript_driver
SessionConfig::OPTIONS.each do |method|
def_delegators :session_options, method, "#{method}="
end
def initialize
@session_options = Capybara::SessionConfig.new
@javascript_driver = nil
end
attr_writer :reuse_server # rubocop:disable Style/BisectedAttrAccessor
def threadsafe=(bool)
if (bool != threadsafe) && Session.instance_created?
raise 'Threadsafe setting cannot be changed once a session is created'
end
@threadsafe = bool
end
##
#
# Return the proc that Capybara will call to run the Rack application.
# The block returned receives a rack app, port, and host/ip and should run a Rack handler
# By default, Capybara will try to use puma.
#
attr_reader :server
##
#
# Set the server to use.
#
# Capybara.server = :webrick
# Capybara.server = :puma, { Silent: true }
#
# @overload server=(name)
# @param [Symbol] name Name of the server type to use
# @overload server=([name, options])
# @param [Symbol] name Name of the server type to use
# @param [Hash] options Options to pass to the server block
# @see register_server
#
def server=(name)
name, options = *name if name.is_a? Array
@server = if name.respond_to? :call
name
elsif options
proc { |app, port, host| Capybara.servers[name.to_sym].call(app, port, host, **options) }
else
Capybara.servers[name.to_sym]
end
end
##
#
# @return [Symbol] The name of the driver to use by default
#
def default_driver
@default_driver || :rack_test
end
##
#
# @return [Symbol] The name of the driver used when JavaScript is needed
#
def javascript_driver
@javascript_driver || :selenium
end
def deprecate(method, alternate_method, once: false)
@deprecation_notified ||= {}
unless once && @deprecation_notified[method]
Capybara::Helpers.warn "DEPRECATED: ##{method} is deprecated, please use ##{alternate_method} instead: #{Capybara::Helpers.filter_backtrace(caller)}"
end
@deprecation_notified[method] = true
end
def allow_gumbo=(val)
deprecate('allow_gumbo=', 'use_html5_parsing=')
self.use_html5_parsing = val
end
def allow_gumbo
deprecate('allow_gumbo', 'use_html5_parsing')
use_html5_parsing
end
end
end
| ruby | MIT | b3325b198464b806f07ec2011ceb532d6d5cf4ab | 2026-01-04T15:38:10.098638Z | false |
teamcapybara/capybara | https://github.com/teamcapybara/capybara/blob/b3325b198464b806f07ec2011ceb532d6d5cf4ab/lib/capybara/server.rb | lib/capybara/server.rb | # frozen_string_literal: true
require 'uri'
require 'net/http'
require 'rack'
require 'capybara/server/middleware'
require 'capybara/server/animation_disabler'
require 'capybara/server/checker'
module Capybara
# @api private
class Server
class << self
def ports
@ports ||= {}
end
end
attr_reader :app, :port, :host
def initialize(app,
*deprecated_options,
port: Capybara.server_port,
host: Capybara.server_host,
reportable_errors: Capybara.server_errors,
extra_middleware: [])
unless deprecated_options.empty?
warn 'Positional arguments, other than the application, to Server#new are deprecated, please use keyword arguments'
end
@app = app
@extra_middleware = extra_middleware
@server_thread = nil # suppress warnings
@host = deprecated_options[1] || host
@reportable_errors = deprecated_options[2] || reportable_errors
@port = deprecated_options[0] || port
@port ||= Capybara::Server.ports[port_key]
@port ||= find_available_port(host)
@checker = Checker.new(@host, @port)
end
def reset_error!
middleware.clear_error
end
def error
middleware.error
end
def using_ssl?
@checker.ssl?
end
def responsive?
return false if @server_thread&.join(0)
res = @checker.request { |http| http.get('/__identify__') }
res.body == app.object_id.to_s if res.is_a?(Net::HTTPSuccess) || res.is_a?(Net::HTTPRedirection)
rescue SystemCallError, Net::ReadTimeout, OpenSSL::SSL::SSLError
false
end
def wait_for_pending_requests
timer = Capybara::Helpers.timer(expire_in: 60)
while pending_requests?
raise "Requests did not finish in 60 seconds: #{middleware.pending_requests}" if timer.expired?
sleep 0.01
end
end
def boot
unless responsive?
Capybara::Server.ports[port_key] = port
@server_thread = Thread.new do
Capybara.server.call(middleware, port, host)
end
timer = Capybara::Helpers.timer(expire_in: 60)
until responsive?
raise 'Rack application timed out during boot' if timer.expired?
@server_thread.join(0.1)
end
end
self
end
def base_url
"http#{'s' if using_ssl?}://#{host}:#{port}"
end
private
def middleware
@middleware ||= Middleware.new(app, @reportable_errors, @extra_middleware)
end
def port_key
Capybara.reuse_server ? app.object_id : middleware.object_id
end
def pending_requests?
middleware.pending_requests?
end
def find_available_port(host)
server = TCPServer.new(host, 0)
port = server.addr[1]
server.close
# Workaround issue where some platforms (mac, ???) when passed a host
# of '0.0.0.0' will return a port that is only available on one of the
# ip addresses that resolves to, but the next binding to that port requires
# that port to be available on all ips
server = TCPServer.new(host, port)
port
rescue Errno::EADDRINUSE
retry
ensure
server&.close
end
end
end
| ruby | MIT | b3325b198464b806f07ec2011ceb532d6d5cf4ab | 2026-01-04T15:38:10.098638Z | false |
teamcapybara/capybara | https://github.com/teamcapybara/capybara/blob/b3325b198464b806f07ec2011ceb532d6d5cf4ab/lib/capybara/rspec.rb | lib/capybara/rspec.rb | # frozen_string_literal: true
require 'rspec/core'
require 'capybara/dsl'
require 'capybara/rspec/matchers'
require 'capybara/rspec/features'
require 'capybara/rspec/matcher_proxies'
RSpec.configure do |config|
config.include Capybara::DSL, type: :feature
config.include Capybara::RSpecMatchers, type: :feature
config.include Capybara::DSL, type: :system
config.include Capybara::RSpecMatchers, type: :system
config.include Capybara::RSpecMatchers, type: :view
# The before and after blocks must run instantaneously, because Capybara
# might not actually be used in all examples where it's included.
config.after do
if self.class.include?(Capybara::DSL)
Capybara.reset_sessions!
Capybara.use_default_driver
end
end
config.before do |example|
if self.class.include?(Capybara::DSL)
Capybara.current_driver = Capybara.javascript_driver if example.metadata[:js]
Capybara.current_driver = example.metadata[:driver] if example.metadata[:driver]
end
end
end
| ruby | MIT | b3325b198464b806f07ec2011ceb532d6d5cf4ab | 2026-01-04T15:38:10.098638Z | false |
teamcapybara/capybara | https://github.com/teamcapybara/capybara/blob/b3325b198464b806f07ec2011ceb532d6d5cf4ab/lib/capybara/minitest/spec.rb | lib/capybara/minitest/spec.rb | # frozen_string_literal: true
require 'minitest/spec'
module Capybara
module Minitest
module Expectations
##
# Expectation that there is an ancestor
#
# @!method must_have_ancestor
# See {Capybara::Node::Matchers#has_ancestor?}
##
# Expectation that there is button
#
# @!method must_have_button
# See {Capybara::Node::Matchers#has_button?}
##
# Expectation that there is no button
#
# @!method wont_have_button
# See {Capybara::Node::Matchers#has_no_button?}
##
# Expectation that there is checked_field
#
# @!method must_have_checked_field
# See {Capybara::Node::Matchers#has_checked_field?}
##
# Expectation that there is no checked_field
#
# @!method wont_have_checked_field
# See {Capybara::Node::Matchers#has_no_checked_field?}
##
# Expectation that there is unchecked_field
#
# @!method must_have_unchecked_field
# See {Capybara::Node::Matchers#has_unchecked_field?}
##
# Expectation that there is no unchecked_field
#
# @!method wont_have_unchecked_field
# See {Capybara::Node::Matchers#has_no_unchecked_field?}
##
# Expectation that page content does match
#
# @!method must_have_content
# See {Capybara::Node::Matchers#has_content?}
##
# Expectation that page content does not match
#
# @!method wont_have_content
# See {Capybara::Node::Matchers#has_no_content?}
##
# Expectation that there is css
#
# @!method must_have_css
# See {Capybara::Node::Matchers#has_css?}
##
# Expectation that there is no css
#
# @!method wont_have_css
# See {Capybara::Node::Matchers#has_no_css?}
##
# Expectation that current path matches
#
# @!method must_have_current_path
# See {Capybara::SessionMatchers#has_current_path?}
##
# Expectation that current page does not match
#
# @!method wont_have_current_path
# See {Capybara::SessionMatchers#has_no_current_path?}
##
# Expectation that there is field
#
# @!method must_have_field
# See {Capybara::Node::Matchers#has_field?}
##
# Expectation that there is no field
#
# @!method wont_have_field
# See {Capybara::Node::Matchers#has_no_field?}
##
# Expectation that there is element
#
# @!method must_have_element
# See {Capybara::Node::Matchers#has_element?}
##
# Expectation that there is no element
#
# @!method wont_have_element
# See {Capybara::Node::Matchers#has_no_element?}
##
# Expectation that there is link
#
# @!method must_have_link
# See {Capybara::Node::Matchers#has_link?}
##
# Expectation that there is no link
#
# @!method wont_have_link
# See {Capybara::Node::Matchers#has_no_link?}
##
# Expectation that page text does match
#
# @!method must_have_text
# See {Capybara::Node::Matchers#has_text?}
##
# Expectation that page text does not match
#
# @!method wont_have_text
# See {Capybara::Node::Matchers#has_no_text?}
##
# Expectation that page title does match
#
# @!method must_have_title
# See {Capybara::Node::DocumentMatchers#has_title?}
##
# Expectation that page title does not match
#
# @!method wont_have_title
# See {Capybara::Node::DocumentMatchers#has_no_title?}
##
# Expectation that there is select
#
# @!method must_have_select
# See {Capybara::Node::Matchers#has_select?}
##
# Expectation that there is no select
#
# @!method wont_have_select
# See {Capybara::Node::Matchers#has_no_select?}
##
# Expectation that there is a selector
#
# @!method must_have_selector
# See {Capybara::Node::Matchers#has_selector?}
##
# Expectation that there is no selector
#
# @!method wont_have_selector
# See {Capybara::Node::Matchers#has_no_selector?}
##
# Expectation that all of the provided selectors are present
#
# @!method must_have_all_of_selectors
# See {Capybara::Node::Matchers#assert_all_of_selectors}
##
# Expectation that none of the provided selectors are present
#
# @!method must_have_none_of_selectors
# See {Capybara::Node::Matchers#assert_none_of_selectors}
##
# Expectation that any of the provided selectors are present
#
# @!method must_have_any_of_selectors
# See {Capybara::Node::Matchers#assert_any_of_selectors}
##
# Expectation that there is a sibling
#
# @!method must_have_sibling
# See {Capybara::Node::Matchers#has_sibling?}
##
# Expectation that element has style
#
# @!method must_match_style
# See {Capybara::Node::Matchers#matches_style?}
##
# Expectation that there is table
#
# @!method must_have_table
# See {Capybara::Node::Matchers#has_table?}
##
# Expectation that there is no table
#
# @!method wont_have_table
# See {Capybara::Node::Matchers#has_no_table?}
##
# Expectation that there is xpath
#
# @!method must_have_xpath
# See {Capybara::Node::Matchers#has_xpath?}
##
# Expectation that there is no xpath
#
# @!method wont_have_xpath
# See {Capybara::Node::Matchers#has_no_xpath?}
# This currently doesn't work for Ruby 2.8 due to Minitest not forwarding keyword args separately
# %w[text content title current_path].each do |assertion|
# infect_an_assertion "assert_#{assertion}", "must_have_#{assertion}", :reverse
# infect_an_assertion "refute_#{assertion}", "wont_have_#{assertion}", :reverse
# end
# rubocop:disable Style/MultilineBlockChain
(%w[text content title current_path
selector xpath css link button field select table checked_field unchecked_field
ancestor sibling].flat_map do |assertion|
[%W[assert_#{assertion} must_have_#{assertion}],
%W[refute_#{assertion} wont_have_#{assertion}]]
end + [%w[assert_all_of_selectors must_have_all_of_selectors],
%w[assert_none_of_selectors must_have_none_of_selectors],
%w[assert_any_of_selectors must_have_any_of_selectors],
%w[assert_matches_style must_match_style]] +
%w[selector xpath css].flat_map do |assertion|
[%W[assert_matches_#{assertion} must_match_#{assertion}],
%W[refute_matches_#{assertion} wont_match_#{assertion}]]
end).each do |(meth, new_name)|
class_eval <<-ASSERTION, __FILE__, __LINE__ + 1
def #{new_name}(...)
::Minitest::Expectation.new(self, ::Minitest::Spec.current).#{new_name}(...)
end
ASSERTION
::Minitest::Expectation.class_eval <<-ASSERTION, __FILE__, __LINE__ + 1
def #{new_name}(...)
raise "Calling ##{new_name} outside of test." unless ctx
ctx.#{meth}(target, ...)
end
ASSERTION
end
# rubocop:enable Style/MultilineBlockChain
##
# @deprecated
def must_have_style(...)
warn 'must_have_style is deprecated, please use must_match_style'
must_match_style(...)
end
end
end
end
class Capybara::Session
include Capybara::Minitest::Expectations unless ENV['MT_NO_EXPECTATIONS']
end
class Capybara::Node::Base
include Capybara::Minitest::Expectations unless ENV['MT_NO_EXPECTATIONS']
end
class Capybara::Node::Simple
include Capybara::Minitest::Expectations unless ENV['MT_NO_EXPECTATIONS']
end
| ruby | MIT | b3325b198464b806f07ec2011ceb532d6d5cf4ab | 2026-01-04T15:38:10.098638Z | false |
teamcapybara/capybara | https://github.com/teamcapybara/capybara/blob/b3325b198464b806f07ec2011ceb532d6d5cf4ab/lib/capybara/rspec/matchers.rb | lib/capybara/rspec/matchers.rb | # frozen_string_literal: true
require 'capybara/rspec/matchers/have_selector'
require 'capybara/rspec/matchers/have_ancestor'
require 'capybara/rspec/matchers/have_sibling'
require 'capybara/rspec/matchers/match_selector'
require 'capybara/rspec/matchers/have_current_path'
require 'capybara/rspec/matchers/match_style'
require 'capybara/rspec/matchers/have_text'
require 'capybara/rspec/matchers/have_title'
require 'capybara/rspec/matchers/become_closed'
module Capybara
module RSpecMatchers
# RSpec matcher for whether the element(s) matching a given selector exist.
#
# @see Capybara::Node::Matchers#assert_selector
def have_selector(...)
Matchers::HaveSelector.new(...)
end
# RSpec matcher for whether the element(s) matching a group of selectors exist.
#
# @see Capybara::Node::Matchers#assert_all_of_selectors
def have_all_of_selectors(...)
Matchers::HaveAllSelectors.new(...)
end
# RSpec matcher for whether no element(s) matching a group of selectors exist.
#
# @see Capybara::Node::Matchers#assert_none_of_selectors
def have_none_of_selectors(...)
Matchers::HaveNoSelectors.new(...)
end
# RSpec matcher for whether the element(s) matching any of a group of selectors exist.
#
# @see Capybara::Node::Matchers#assert_any_of_selectors
def have_any_of_selectors(...)
Matchers::HaveAnySelectors.new(...)
end
# RSpec matcher for whether the current element matches a given selector.
#
# @see Capybara::Node::Matchers#assert_matches_selector
def match_selector(...)
Matchers::MatchSelector.new(...)
end
%i[css xpath].each do |selector|
define_method "have_#{selector}" do |expr, **options, &optional_filter_block|
Matchers::HaveSelector.new(selector, expr, **options, &optional_filter_block)
end
define_method "match_#{selector}" do |expr, **options, &optional_filter_block|
Matchers::MatchSelector.new(selector, expr, **options, &optional_filter_block)
end
end
# @!method have_xpath(xpath, **options, &optional_filter_block)
# RSpec matcher for whether elements(s) matching a given xpath selector exist.
#
# @see Capybara::Node::Matchers#has_xpath?
# @!method have_css(css, **options, &optional_filter_block)
# RSpec matcher for whether elements(s) matching a given css selector exist
#
# @see Capybara::Node::Matchers#has_css?
# @!method match_xpath(xpath, **options, &optional_filter_block)
# RSpec matcher for whether the current element matches a given xpath selector.
#
# @see Capybara::Node::Matchers#matches_xpath?
# @!method match_css(css, **options, &optional_filter_block)
# RSpec matcher for whether the current element matches a given css selector.
#
# @see Capybara::Node::Matchers#matches_css?
%i[link button field select table element].each do |selector|
define_method "have_#{selector}" do |locator = nil, **options, &optional_filter_block|
Matchers::HaveSelector.new(selector, locator, **options, &optional_filter_block)
end
end
# @!method have_element(locator = nil, **options, &optional_filter_block)
# RSpec matcher for elements.
#
# @see Capybara::Node::Matchers#has_element?
# @!method have_link(locator = nil, **options, &optional_filter_block)
# RSpec matcher for links.
#
# @see Capybara::Node::Matchers#has_link?
# @!method have_button(locator = nil, **options, &optional_filter_block)
# RSpec matcher for buttons.
#
# @see Capybara::Node::Matchers#has_button?
# @!method have_field(locator = nil, **options, &optional_filter_block)
# RSpec matcher for form fields.
#
# @see Capybara::Node::Matchers#has_field?
# @!method have_select(locator = nil, **options, &optional_filter_block)
# RSpec matcher for select elements.
#
# @see Capybara::Node::Matchers#has_select?
# @!method have_table(locator = nil, **options, &optional_filter_block)
# RSpec matcher for table elements.
#
# @see Capybara::Node::Matchers#has_table?
%i[checked unchecked].each do |state|
define_method "have_#{state}_field" do |locator = nil, **options, &optional_filter_block|
Matchers::HaveSelector.new(:field, locator, **options.merge(state => true), &optional_filter_block)
end
end
# @!method have_checked_field(locator = nil, **options, &optional_filter_block)
# RSpec matcher for checked fields.
#
# @see Capybara::Node::Matchers#has_checked_field?
# @!method have_unchecked_field(locator = nil, **options, &optional_filter_block)
# RSpec matcher for unchecked fields.
#
# @see Capybara::Node::Matchers#has_unchecked_field?
# RSpec matcher for text content.
#
# @see Capybara::Node::Matchers#assert_text
def have_text(text_or_type, *args, **options)
Matchers::HaveText.new(text_or_type, *args, **options)
end
alias_method :have_content, :have_text
def have_title(title, **options)
Matchers::HaveTitle.new(title, **options)
end
# RSpec matcher for the current path.
#
# @see Capybara::SessionMatchers#assert_current_path
def have_current_path(path, **options, &optional_filter_block)
Matchers::HaveCurrentPath.new(path, **options, &optional_filter_block)
end
# RSpec matcher for element style.
#
# @see Capybara::Node::Matchers#matches_style?
def match_style(styles = nil, **options)
styles, options = options, {} if styles.nil?
Matchers::MatchStyle.new(styles, **options)
end
##
# @deprecated
#
def have_style(styles = nil, **options)
Capybara::Helpers.warn "DEPRECATED: have_style is deprecated, please use match_style : #{Capybara::Helpers.filter_backtrace(caller)}"
match_style(styles, **options)
end
%w[selector css xpath text title current_path link button
field checked_field unchecked_field select table
sibling ancestor element].each do |matcher_type|
define_method "have_no_#{matcher_type}" do |*args, **kw_args, &optional_filter_block|
Matchers::NegatedMatcher.new(send("have_#{matcher_type}", *args, **kw_args, &optional_filter_block))
end
end
alias_method :have_no_content, :have_no_text
%w[selector css xpath].each do |matcher_type|
define_method "not_match_#{matcher_type}" do |*args, **kw_args, &optional_filter_block|
Matchers::NegatedMatcher.new(send("match_#{matcher_type}", *args, **kw_args, &optional_filter_block))
end
end
# RSpec matcher for whether sibling element(s) matching a given selector exist.
#
# @see Capybara::Node::Matchers#assert_sibling
def have_sibling(...)
Matchers::HaveSibling.new(...)
end
# RSpec matcher for whether ancestor element(s) matching a given selector exist.
#
# @see Capybara::Node::Matchers#assert_ancestor
def have_ancestor(...)
Matchers::HaveAncestor.new(...)
end
##
# Wait for window to become closed.
#
# @example
# expect(window).to become_closed(wait: 0.8)
#
# @option options [Numeric] :wait Maximum wait time. Defaults to {Capybara.configure default_max_wait_time}
def become_closed(**options)
Matchers::BecomeClosed.new(options)
end
end
end
| ruby | MIT | b3325b198464b806f07ec2011ceb532d6d5cf4ab | 2026-01-04T15:38:10.098638Z | false |
teamcapybara/capybara | https://github.com/teamcapybara/capybara/blob/b3325b198464b806f07ec2011ceb532d6d5cf4ab/lib/capybara/rspec/matcher_proxies.rb | lib/capybara/rspec/matcher_proxies.rb | # frozen_string_literal: true
module Capybara
module RSpecMatcherProxies
def all(*args, **kwargs, &block)
if defined?(::RSpec::Matchers::BuiltIn::All) && args.first.respond_to?(:matches?)
::RSpec::Matchers::BuiltIn::All.new(*args)
else
find_all(*args, **kwargs, &block)
end
end
def within(*args, **kwargs, &block)
if block
within_element(*args, **kwargs, &block)
else
be_within(*args)
end
end
end
end
if RUBY_ENGINE == 'jruby'
# :nocov:
module Capybara::DSL
class << self
remove_method :included
def included(base)
warn 'including Capybara::DSL in the global scope is not recommended!' if base == Object
if defined?(::RSpec::Matchers) && base.include?(::RSpec::Matchers)
base.send(:include, ::Capybara::RSpecMatcherProxies)
end
super
end
end
end
if defined?(RSpec::Matchers)
module ::RSpec::Matchers
def self.included(base)
base.send(:include, ::Capybara::RSpecMatcherProxies) if base.include?(::Capybara::DSL)
super
end
end
end
# :nocov:
else
module Capybara::DSLRSpecProxyInstaller
module ClassMethods
def included(base)
base.include(::Capybara::RSpecMatcherProxies) if defined?(::RSpec::Matchers) && base.include?(::RSpec::Matchers)
super
end
end
def self.prepended(base)
class << base
prepend ClassMethods
end
end
end
module Capybara::RSpecMatcherProxyInstaller
module ClassMethods
def included(base)
base.include(::Capybara::RSpecMatcherProxies) if base.include?(::Capybara::DSL)
super
end
end
def self.prepended(base)
class << base
prepend ClassMethods
end
end
end
Capybara::DSL.prepend Capybara::DSLRSpecProxyInstaller
RSpec::Matchers.prepend Capybara::RSpecMatcherProxyInstaller if defined?(RSpec::Matchers)
end
| ruby | MIT | b3325b198464b806f07ec2011ceb532d6d5cf4ab | 2026-01-04T15:38:10.098638Z | false |
teamcapybara/capybara | https://github.com/teamcapybara/capybara/blob/b3325b198464b806f07ec2011ceb532d6d5cf4ab/lib/capybara/rspec/features.rb | lib/capybara/rspec/features.rb | # frozen_string_literal: true
RSpec.shared_context 'Capybara Features', capybara_feature: true do
instance_eval do
alias background before
alias given let
alias given! let!
end
end
# ensure shared_context is included if default shared_context_metadata_behavior is changed
RSpec.configure do |config|
config.include_context 'Capybara Features', capybara_feature: true if config.respond_to?(:include_context)
end
RSpec.configure do |config|
config.alias_example_group_to :feature, :capybara_feature, type: :feature
config.alias_example_group_to :xfeature, :capybara_feature, type: :feature, skip: 'Temporarily disabled with xfeature'
config.alias_example_group_to :ffeature, :capybara_feature, :focus, type: :feature
config.alias_example_to :scenario
config.alias_example_to :xscenario, skip: 'Temporarily disabled with xscenario'
config.alias_example_to :fscenario, :focus
end
| ruby | MIT | b3325b198464b806f07ec2011ceb532d6d5cf4ab | 2026-01-04T15:38:10.098638Z | false |
teamcapybara/capybara | https://github.com/teamcapybara/capybara/blob/b3325b198464b806f07ec2011ceb532d6d5cf4ab/lib/capybara/rspec/matchers/count_sugar.rb | lib/capybara/rspec/matchers/count_sugar.rb | # frozen_string_literal: true
module Capybara
module RSpecMatchers
module CountSugar
def once; exactly(1); end
def twice; exactly(2); end
def thrice; exactly(3); end
def exactly(number)
options[:count] = number
self
end
def at_most(number)
options[:maximum] = number
self
end
def at_least(number)
options[:minimum] = number
self
end
def times
self
end
private
def options
# (@args.last.is_a?(Hash) ? @args : @args.push({})).last
@kw_args
end
end
end
end
| ruby | MIT | b3325b198464b806f07ec2011ceb532d6d5cf4ab | 2026-01-04T15:38:10.098638Z | false |
teamcapybara/capybara | https://github.com/teamcapybara/capybara/blob/b3325b198464b806f07ec2011ceb532d6d5cf4ab/lib/capybara/rspec/matchers/have_text.rb | lib/capybara/rspec/matchers/have_text.rb | # frozen_string_literal: true
require 'capybara/rspec/matchers/base'
module Capybara
module RSpecMatchers
module Matchers
class HaveText < CountableWrappedElementMatcher
def element_matches?(el)
el.assert_text(*@args, **@kw_args)
end
def element_does_not_match?(el)
el.assert_no_text(*@args, **@kw_args)
end
def description
"have text #{format(text)}"
end
def format(content)
content.inspect
end
private
def text
@args[0].is_a?(Symbol) ? @args[1] : @args[0]
end
end
end
end
end
| ruby | MIT | b3325b198464b806f07ec2011ceb532d6d5cf4ab | 2026-01-04T15:38:10.098638Z | false |
teamcapybara/capybara | https://github.com/teamcapybara/capybara/blob/b3325b198464b806f07ec2011ceb532d6d5cf4ab/lib/capybara/rspec/matchers/have_ancestor.rb | lib/capybara/rspec/matchers/have_ancestor.rb | # frozen_string_literal: true
require 'capybara/rspec/matchers/base'
module Capybara
module RSpecMatchers
module Matchers
class HaveAncestor < CountableWrappedElementMatcher
def element_matches?(el)
el.assert_ancestor(*@args, **session_query_options, &@filter_block)
end
def element_does_not_match?(el)
el.assert_no_ancestor(*@args, **session_query_options, &@filter_block)
end
def description
"have ancestor #{query.description}"
end
def query
# @query ||= Capybara::Queries::AncestorQuery.new(*session_query_args, &@filter_block)
@query ||= Capybara::Queries::AncestorQuery.new(*session_query_args, **session_query_options, &@filter_block)
end
end
end
end
end
| ruby | MIT | b3325b198464b806f07ec2011ceb532d6d5cf4ab | 2026-01-04T15:38:10.098638Z | false |
teamcapybara/capybara | https://github.com/teamcapybara/capybara/blob/b3325b198464b806f07ec2011ceb532d6d5cf4ab/lib/capybara/rspec/matchers/have_sibling.rb | lib/capybara/rspec/matchers/have_sibling.rb | # frozen_string_literal: true
require 'capybara/rspec/matchers/base'
module Capybara
module RSpecMatchers
module Matchers
class HaveSibling < CountableWrappedElementMatcher
def element_matches?(el)
el.assert_sibling(*@args, **session_query_options, &@filter_block)
end
def element_does_not_match?(el)
el.assert_no_sibling(*@args, **session_query_options, &@filter_block)
end
def description
"have sibling #{query.description}"
end
def query
@query ||= Capybara::Queries::SiblingQuery.new(*session_query_args, **session_query_options, &@filter_block)
end
end
end
end
end
| ruby | MIT | b3325b198464b806f07ec2011ceb532d6d5cf4ab | 2026-01-04T15:38:10.098638Z | false |
teamcapybara/capybara | https://github.com/teamcapybara/capybara/blob/b3325b198464b806f07ec2011ceb532d6d5cf4ab/lib/capybara/rspec/matchers/have_selector.rb | lib/capybara/rspec/matchers/have_selector.rb | # frozen_string_literal: true
# rubocop:disable Naming/PredicatePrefix
require 'capybara/rspec/matchers/base'
module Capybara
module RSpecMatchers
module Matchers
class HaveSelector < CountableWrappedElementMatcher
def initialize(*args, **kw_args, &filter_block)
super
return unless (@args.size < 2) && @kw_args.keys.any?(String)
@args.push(@kw_args)
@kw_args = {}
end
def element_matches?(el)
el.assert_selector(*@args, **session_query_options, &@filter_block)
end
def element_does_not_match?(el)
el.assert_no_selector(*@args, **session_query_options, &@filter_block)
end
def description = "have #{query.description}"
def query
@query ||= Capybara::Queries::SelectorQuery.new(*session_query_args, **session_query_options, &@filter_block)
end
end
class HaveAllSelectors < WrappedElementMatcher
def element_matches?(el)
el.assert_all_of_selectors(*@args, **session_query_options, &@filter_block)
end
def does_not_match?(_actual)
raise ArgumentError, 'The have_all_selectors matcher does not support use with not_to/should_not'
end
def description = 'have all selectors'
end
class HaveNoSelectors < WrappedElementMatcher
def element_matches?(el)
el.assert_none_of_selectors(*@args, **session_query_options, &@filter_block)
end
def does_not_match?(_actual)
raise ArgumentError, 'The have_none_of_selectors matcher does not support use with not_to/should_not'
end
def description = 'have no selectors'
end
class HaveAnySelectors < WrappedElementMatcher
def element_matches?(el)
el.assert_any_of_selectors(*@args, **session_query_options, &@filter_block)
end
def does_not_match?(el)
el.assert_none_of_selectors(*@args, **session_query_options, &@filter_block)
end
def description = 'have any selectors'
end
end
end
end
# rubocop:enable Naming/PredicatePrefix
| ruby | MIT | b3325b198464b806f07ec2011ceb532d6d5cf4ab | 2026-01-04T15:38:10.098638Z | false |
teamcapybara/capybara | https://github.com/teamcapybara/capybara/blob/b3325b198464b806f07ec2011ceb532d6d5cf4ab/lib/capybara/rspec/matchers/match_selector.rb | lib/capybara/rspec/matchers/match_selector.rb | # frozen_string_literal: true
require 'capybara/rspec/matchers/have_selector'
module Capybara
module RSpecMatchers
module Matchers
class MatchSelector < HaveSelector
def element_matches?(el)
el.assert_matches_selector(*@args, **session_query_options, &@filter_block)
end
def element_does_not_match?(el)
el.assert_not_matches_selector(*@args, **session_query_options, &@filter_block)
end
def description
"match #{query.description}"
end
def query
@query ||= Capybara::Queries::MatchQuery.new(*session_query_args, **session_query_options, &@filter_block)
end
end
end
end
end
| ruby | MIT | b3325b198464b806f07ec2011ceb532d6d5cf4ab | 2026-01-04T15:38:10.098638Z | false |
teamcapybara/capybara | https://github.com/teamcapybara/capybara/blob/b3325b198464b806f07ec2011ceb532d6d5cf4ab/lib/capybara/rspec/matchers/have_title.rb | lib/capybara/rspec/matchers/have_title.rb | # frozen_string_literal: true
require 'capybara/rspec/matchers/base'
module Capybara
module RSpecMatchers
module Matchers
class HaveTitle < WrappedElementMatcher
def element_matches?(el)
el.assert_title(*@args, **@kw_args)
end
def element_does_not_match?(el)
el.assert_no_title(*@args, **@kw_args)
end
def description
"have title #{title.inspect}"
end
private
def title
@args.first
end
end
end
end
end
| ruby | MIT | b3325b198464b806f07ec2011ceb532d6d5cf4ab | 2026-01-04T15:38:10.098638Z | false |
teamcapybara/capybara | https://github.com/teamcapybara/capybara/blob/b3325b198464b806f07ec2011ceb532d6d5cf4ab/lib/capybara/rspec/matchers/have_current_path.rb | lib/capybara/rspec/matchers/have_current_path.rb | # frozen_string_literal: true
require 'capybara/rspec/matchers/base'
module Capybara
module RSpecMatchers
module Matchers
class HaveCurrentPath < WrappedElementMatcher
def element_matches?(el)
el.assert_current_path(current_path, **@kw_args, &@filter_block)
end
def element_does_not_match?(el)
el.assert_no_current_path(current_path, **@kw_args, &@filter_block)
end
def description
"have current path #{current_path.inspect}"
end
private
def current_path
@args.first
end
end
end
end
end
| ruby | MIT | b3325b198464b806f07ec2011ceb532d6d5cf4ab | 2026-01-04T15:38:10.098638Z | false |
teamcapybara/capybara | https://github.com/teamcapybara/capybara/blob/b3325b198464b806f07ec2011ceb532d6d5cf4ab/lib/capybara/rspec/matchers/base.rb | lib/capybara/rspec/matchers/base.rb | # frozen_string_literal: true
require 'capybara/rspec/matchers/compound'
require 'capybara/rspec/matchers/count_sugar'
require 'capybara/rspec/matchers/spatial_sugar'
module Capybara
module RSpecMatchers
module Matchers
class Base
include ::Capybara::RSpecMatchers::Matchers::Compound if defined?(::Capybara::RSpecMatchers::Matchers::Compound)
attr_reader :failure_message, :failure_message_when_negated
def initialize(*args, **kw_args, &filter_block)
@args = args.dup
@kw_args = kw_args || {}
@filter_block = filter_block
end
private
def session_query_args
# if @args.last.is_a? Hash
# @args.last[:session_options] = session_options
# else
# @args.push(session_options: session_options)
# end
@args
end
def session_query_options
@kw_args[:session_options] = session_options
@kw_args
end
def session_options
@context_el ||= nil
if @context_el.respond_to? :session_options
@context_el.session_options
elsif @context_el.respond_to? :current_scope
@context_el.current_scope.session_options
else
Capybara.session_options
end
end
end
class WrappedElementMatcher < Base
def matches?(actual, &filter_block)
@filter_block ||= filter_block
element_matches?(wrap(actual))
rescue Capybara::ExpectationNotMet => e
@failure_message = e.message
false
end
def does_not_match?(actual, &filter_block)
@filter_block ||= filter_block
element_does_not_match?(wrap(actual))
rescue Capybara::ExpectationNotMet => e
@failure_message_when_negated = e.message
false
end
private
def wrap(actual)
actual = actual.to_capybara_node if actual.respond_to?(:to_capybara_node)
@context_el = if actual.respond_to?(:has_selector?)
actual
else
Capybara.string(actual.to_s)
end
end
end
class CountableWrappedElementMatcher < WrappedElementMatcher
include ::Capybara::RSpecMatchers::CountSugar
include ::Capybara::RSpecMatchers::SpatialSugar
end
class NegatedMatcher
include ::Capybara::RSpecMatchers::Matchers::Compound if defined?(::Capybara::RSpecMatchers::Matchers::Compound)
def initialize(matcher)
super()
@matcher = matcher
end
def matches?(actual, &filter_block)
@matcher.does_not_match?(actual, &filter_block)
end
def does_not_match?(actual, &filter_block)
@matcher.matches?(actual, &filter_block)
end
def description
"not #{@matcher.description}"
end
def failure_message
@matcher.failure_message_when_negated
end
def failure_message_when_negated
@matcher.failure_message
end
end
end
end
end
| ruby | MIT | b3325b198464b806f07ec2011ceb532d6d5cf4ab | 2026-01-04T15:38:10.098638Z | false |
teamcapybara/capybara | https://github.com/teamcapybara/capybara/blob/b3325b198464b806f07ec2011ceb532d6d5cf4ab/lib/capybara/rspec/matchers/compound.rb | lib/capybara/rspec/matchers/compound.rb | # frozen_string_literal: true
if defined?(RSpec::Expectations::Version)
module Capybara
module RSpecMatchers
module Matchers
module Compound
include ::RSpec::Matchers::Composable
def and(matcher)
And.new(self, matcher)
end
def and_then(matcher)
::RSpec::Matchers::BuiltIn::Compound::And.new(self, matcher)
end
def or(matcher)
Or.new(self, matcher)
end
class CapybaraEvaluator
def initialize(actual)
@actual = actual
@match_results = Hash.new { |hsh, matcher| hsh[matcher] = matcher.matches?(@actual) }
end
def matcher_matches?(matcher)
@match_results[matcher]
end
def reset
@match_results.clear
end
end
# @api private
module Synchronizer
def match(_expected, actual)
@evaluator = CapybaraEvaluator.new(actual)
syncer = sync_element(actual)
begin
syncer.synchronize do
@evaluator.reset
raise ::Capybara::ElementNotFound unless synchronized_match?
true
end
rescue StandardError
false
end
end
def sync_element(el)
if el.respond_to? :synchronize
el
elsif el.respond_to? :current_scope
el.current_scope
else
Capybara.string(el)
end
end
end
class And < ::RSpec::Matchers::BuiltIn::Compound::And
include Synchronizer
private
def synchronized_match?
[matcher_1_matches?, matcher_2_matches?].all?
end
end
class Or < ::RSpec::Matchers::BuiltIn::Compound::Or
include Synchronizer
private
def synchronized_match?
[matcher_1_matches?, matcher_2_matches?].any?
end
end
end
end
end
end
end
| ruby | MIT | b3325b198464b806f07ec2011ceb532d6d5cf4ab | 2026-01-04T15:38:10.098638Z | false |
teamcapybara/capybara | https://github.com/teamcapybara/capybara/blob/b3325b198464b806f07ec2011ceb532d6d5cf4ab/lib/capybara/rspec/matchers/match_style.rb | lib/capybara/rspec/matchers/match_style.rb | # frozen_string_literal: true
require 'capybara/rspec/matchers/base'
module Capybara
module RSpecMatchers
module Matchers
class MatchStyle < WrappedElementMatcher
def initialize(styles = nil, **kw_args, &filter_block)
styles, kw_args = kw_args, {} if styles.nil?
super(styles, **kw_args, &filter_block)
end
def element_matches?(el)
el.assert_matches_style(*@args, **@kw_args)
end
def does_not_match?(_actual)
raise ArgumentError, 'The match_style matcher does not support use with not_to/should_not'
end
def description
'match style'
end
end
end
end
end
module Capybara
module RSpecMatchers
module Matchers
##
# @deprecated
class HaveStyle < MatchStyle
def initialize(*args, **kw_args, &filter_block)
warn 'HaveStyle matcher is deprecated, please use the MatchStyle matcher instead'
super
end
end
end
end
end
| ruby | MIT | b3325b198464b806f07ec2011ceb532d6d5cf4ab | 2026-01-04T15:38:10.098638Z | false |
teamcapybara/capybara | https://github.com/teamcapybara/capybara/blob/b3325b198464b806f07ec2011ceb532d6d5cf4ab/lib/capybara/rspec/matchers/spatial_sugar.rb | lib/capybara/rspec/matchers/spatial_sugar.rb | # frozen_string_literal: true
module Capybara
module RSpecMatchers
module SpatialSugar
def above(el)
options[:above] = el
self
end
def below(el)
options[:below] = el
self
end
def left_of(el)
options[:left_of] = el
self
end
def right_of(el)
options[:right_of] = el
self
end
def near(el)
options[:near] = el
self
end
private
def options
# (@args.last.is_a?(Hash) ? @args : @args.push({})).last
@kw_args
end
end
end
end
| ruby | MIT | b3325b198464b806f07ec2011ceb532d6d5cf4ab | 2026-01-04T15:38:10.098638Z | false |
teamcapybara/capybara | https://github.com/teamcapybara/capybara/blob/b3325b198464b806f07ec2011ceb532d6d5cf4ab/lib/capybara/rspec/matchers/become_closed.rb | lib/capybara/rspec/matchers/become_closed.rb | # frozen_string_literal: true
module Capybara
module RSpecMatchers
module Matchers
class BecomeClosed
def initialize(options)
@options = options
end
def matches?(window)
@window = window
@wait_time = Capybara::Queries::BaseQuery.wait(@options, window.session.config.default_max_wait_time)
timer = Capybara::Helpers.timer(expire_in: @wait_time)
while window.exists?
return false if timer.expired?
sleep 0.01
end
true
end
def failure_message
"expected #{@window.inspect} to become closed after #{@wait_time} seconds"
end
def failure_message_when_negated
"expected #{@window.inspect} not to become closed after #{@wait_time} seconds"
end
end
end
end
end
| ruby | MIT | b3325b198464b806f07ec2011ceb532d6d5cf4ab | 2026-01-04T15:38:10.098638Z | false |
teamcapybara/capybara | https://github.com/teamcapybara/capybara/blob/b3325b198464b806f07ec2011ceb532d6d5cf4ab/lib/capybara/selenium/driver.rb | lib/capybara/selenium/driver.rb | # frozen_string_literal: true
require 'uri'
require 'English'
class Capybara::Selenium::Driver < Capybara::Driver::Base
include Capybara::Selenium::Find
DEFAULT_OPTIONS = {
browser: :firefox,
clear_local_storage: nil,
clear_session_storage: nil
}.freeze
SPECIAL_OPTIONS = %i[browser clear_local_storage clear_session_storage timeout native_displayed].freeze
CAPS_VERSION = Gem::Requirement.new('< 4.8.0')
attr_reader :app, :options
class << self
attr_reader :selenium_webdriver_version
def load_selenium
require 'selenium-webdriver'
require 'capybara/selenium/patches/atoms'
require 'capybara/selenium/patches/is_displayed'
# Look up the version of `selenium-webdriver` to
# see if it's a version we support.
#
# By default, we use Gem.loaded_specs to determine
# the version number. However, in some cases, such
# as when loading `selenium-webdriver` outside of
# Rubygems, we fall back to referencing
# Selenium::WebDriver::VERSION. Ideally we'd
# use the constant in all cases, but earlier versions
# of `selenium-webdriver` didn't provide the constant.
@selenium_webdriver_version =
if Gem.loaded_specs['selenium-webdriver']
Gem.loaded_specs['selenium-webdriver'].version
else
Gem::Version.new(Selenium::WebDriver::VERSION)
end
unless Gem::Requirement.new('>= 4.8').satisfied_by? @selenium_webdriver_version
warn "Warning: You're using an unsupported version of selenium-webdriver, please upgrade to 4.8+."
end
@selenium_webdriver_version
rescue LoadError => e
raise e unless e.message.include?('selenium-webdriver')
raise LoadError, "Capybara's selenium driver is unable to load `selenium-webdriver`, please install the gem and add `gem 'selenium-webdriver'` to your Gemfile if you are using bundler."
end
attr_reader :specializations
def register_specialization(browser_name, specialization)
@specializations ||= {}
@specializations[browser_name] = specialization
end
end
def browser
unless @browser
options[:http_client] ||= begin
require 'capybara/selenium/patches/persistent_client'
if options[:timeout]
::Capybara::Selenium::PersistentClient.new(read_timeout: options[:timeout])
else
::Capybara::Selenium::PersistentClient.new
end
end
processed_options = options.except(*SPECIAL_OPTIONS)
@browser = Selenium::WebDriver.for(options[:browser], processed_options)
specialize_driver
setup_exit_handler
end
@browser
end
def initialize(app, **options)
super()
self.class.load_selenium
@app = app
@browser = nil
@exit_status = nil
@frame_handles = Hash.new { |hash, handle| hash[handle] = [] }
@options = DEFAULT_OPTIONS.merge(options)
@node_class = ::Capybara::Selenium::Node
end
def visit(path)
browser.navigate.to(path)
end
def refresh
browser.navigate.refresh
end
def go_back
browser.navigate.back
end
def go_forward
browser.navigate.forward
end
def html
browser.page_source
rescue Selenium::WebDriver::Error::JavascriptError => e
raise unless e.message.include?('documentElement is null')
end
def title
browser.title
end
def current_url
browser.current_url
end
def wait?; true; end
def needs_server?; true; end
def execute_script(script, *args)
browser.execute_script(script, *native_args(args))
end
def evaluate_script(script, *args)
result = execute_script("return #{script}", *args)
unwrap_script_result(result)
end
def evaluate_async_script(script, *args)
browser.manage.timeouts.script_timeout = Capybara.default_max_wait_time
result = browser.execute_async_script(script, *native_args(args))
unwrap_script_result(result)
end
def active_element
build_node(native_active_element)
end
def send_keys(*args)
# Should this call the specialized nodes rather than native???
native_active_element.send_keys(*args)
end
def save_screenshot(path, **options)
browser.save_screenshot(path, **options)
end
def reset!
# Use instance variable directly so we avoid starting the browser just to reset the session
return unless @browser
navigated = false
timer = Capybara::Helpers.timer(expire_in: 10)
begin
# Only trigger a navigation if we haven't done it already, otherwise it
# can trigger an endless series of unload modals
reset_browser_state unless navigated
navigated = true
# Ensure the page is empty and trigger an UnhandledAlertError for any modals that appear during unload
wait_for_empty_page(timer)
rescue *unhandled_alert_errors
# This error is thrown if an unhandled alert is on the page
# Firefox appears to automatically dismiss this alert, chrome does not
# We'll try to accept it
accept_unhandled_reset_alert
# try cleaning up the browser again
retry
end
end
def frame_obscured_at?(x:, y:)
frame = @frame_handles[current_window_handle].last
return false unless frame
switch_to_frame(:parent)
begin
frame.base.obscured?(x: x, y: y)
ensure
switch_to_frame(frame)
end
end
def switch_to_frame(frame)
handles = @frame_handles[current_window_handle]
case frame
when :top
handles.clear
browser.switch_to.default_content
when :parent
handles.pop
browser.switch_to.parent_frame
else
handles << frame
browser.switch_to.frame(frame.native)
end
end
def current_window_handle
browser.window_handle
end
def window_size(handle)
within_given_window(handle) do
size = browser.manage.window.size
[size.width, size.height]
end
end
def resize_window_to(handle, width, height)
within_given_window(handle) do
browser.manage.window.resize_to(width, height)
end
end
def maximize_window(handle)
within_given_window(handle) do
browser.manage.window.maximize
end
sleep 0.1 # work around for https://code.google.com/p/selenium/issues/detail?id=7405
end
def fullscreen_window(handle)
within_given_window(handle) do
browser.manage.window.full_screen
end
end
def close_window(handle)
raise ArgumentError, 'Not allowed to close the primary window' if handle == window_handles.first
within_given_window(handle) do
browser.close
end
end
def window_handles
browser.window_handles
end
def open_new_window(kind = :tab)
if browser.switch_to.respond_to?(:new_window)
handle = current_window_handle
browser.switch_to.new_window(kind)
switch_to_window(handle)
else
browser.manage.new_window(kind)
end
rescue NoMethodError, Selenium::WebDriver::Error::WebDriverError
# If not supported by the driver or browser default to using JS
browser.execute_script('window.open();')
end
def switch_to_window(handle)
browser.switch_to.window handle
end
def accept_modal(_type, **options)
yield if block_given?
modal = find_modal(**options)
modal.send_keys options[:with] if options[:with]
message = modal.text
modal.accept
message
end
def dismiss_modal(_type, **options)
yield if block_given?
modal = find_modal(**options)
message = modal.text
modal.dismiss
message
end
def quit
@browser&.quit
rescue Selenium::WebDriver::Error::SessionNotCreatedError, Errno::ECONNREFUSED,
Selenium::WebDriver::Error::InvalidSessionIdError
# Browser must have already gone
rescue Selenium::WebDriver::Error::UnknownError => e
unless silenced_unknown_error_message?(e.message) # Most likely already gone
# probably already gone but not sure - so warn
warn "Ignoring Selenium UnknownError during driver quit: #{e.message}"
end
ensure
@browser = nil
end
def invalid_element_errors
@invalid_element_errors ||=
[
::Selenium::WebDriver::Error::StaleElementReferenceError,
::Selenium::WebDriver::Error::ElementNotInteractableError,
::Selenium::WebDriver::Error::InvalidSelectorError, # Work around chromedriver go_back/go_forward race condition
::Selenium::WebDriver::Error::ElementClickInterceptedError,
::Selenium::WebDriver::Error::NoSuchElementError, # IE
::Selenium::WebDriver::Error::InvalidArgumentError # IE
].tap do |errors|
if defined?(::Selenium::WebDriver::Error::DetachedShadowRootError)
errors.push(::Selenium::WebDriver::Error::DetachedShadowRootError)
end
end
end
def no_such_window_error
Selenium::WebDriver::Error::NoSuchWindowError
end
private
def native_args(args)
args.map { |arg| arg.is_a?(Capybara::Selenium::Node) ? arg.native : arg }
end
def native_active_element
browser.switch_to.active_element
end
def clear_browser_state
delete_all_cookies
clear_storage
rescue *clear_browser_state_errors
# delete_all_cookies fails when we've previously gone
# to about:blank, so we rescue this error and do nothing
# instead.
end
def clear_browser_state_errors
@clear_browser_state_errors ||= [Selenium::WebDriver::Error::UnknownError]
end
def unhandled_alert_errors
@unhandled_alert_errors ||= [Selenium::WebDriver::Error::UnexpectedAlertOpenError]
end
def delete_all_cookies
@browser.manage.delete_all_cookies
end
def clear_storage
clear_session_storage unless options[:clear_session_storage] == false
clear_local_storage unless options[:clear_local_storage] == false
rescue Selenium::WebDriver::Error::JavascriptError, Selenium::WebDriver::Error::WebDriverError
# session/local storage may not be available if on non-http pages (e.g. about:blank)
end
def clear_session_storage
if @browser.respond_to? :session_storage
@browser.session_storage.clear
else
begin
@browser&.execute_script('window.sessionStorage.clear()')
rescue # rubocop:disable Style/RescueStandardError
unless options[:clear_session_storage].nil?
warn 'sessionStorage clear requested but is not supported by this driver'
end
end
end
end
def clear_local_storage
# selenium-webdriver 4.30.0 removed HTML5 storage accessors -- not really sure why
# can we replicate this robustly via CDP?
if @browser.respond_to? :local_storage
@browser.local_storage.clear
else
begin
@browser&.execute_script('window.localStorage.clear()')
rescue # rubocop:disable Style/RescueStandardError
unless options[:clear_local_storage].nil?
warn 'localStorage clear requested but is not supported by this driver'
end
end
end
end
def navigate_with_accept(url)
@browser.navigate.to(url)
sleep 0.1 # slight wait for alert
@browser.switch_to.alert.accept
rescue modal_error
# alert now gone, should mean navigation happened
end
def modal_error
Selenium::WebDriver::Error::NoSuchAlertError
end
def within_given_window(handle)
original_handle = current_window_handle
if handle == original_handle
yield
else
switch_to_window(handle)
result = yield
switch_to_window(original_handle)
result
end
end
def find_modal(text: nil, **options)
# Selenium has its own built in wait (2 seconds)for a modal to show up, so this wait is really the minimum time
# Actual wait time may be longer than specified
wait = Selenium::WebDriver::Wait.new(
timeout: options.fetch(:wait, session_options.default_max_wait_time) || 0,
ignore: modal_error
)
begin
wait.until do
alert = @browser.switch_to.alert
regexp = text.is_a?(Regexp) ? text : Regexp.new(Regexp.escape(text.to_s))
matched = alert.text.match?(regexp)
unless matched
raise Capybara::ModalNotFound, "Unable to find modal dialog with #{text} - found '#{alert.text}' instead."
end
alert
end
rescue *find_modal_errors
raise Capybara::ModalNotFound, "Unable to find modal dialog#{" with #{text}" if text}"
end
end
def find_modal_errors
@find_modal_errors ||= [Selenium::WebDriver::Error::TimeoutError]
end
def silenced_unknown_error_message?(msg)
silenced_unknown_error_messages.any? { |regex| msg.match? regex }
end
def silenced_unknown_error_messages
[/Error communicating with the remote browser/]
end
def unwrap_script_result(arg)
case arg
when Array
arg.map { |arr| unwrap_script_result(arr) }
when Hash
arg.transform_values! { |value| unwrap_script_result(value) }
when Selenium::WebDriver::Element, Selenium::WebDriver::ShadowRoot
build_node(arg)
else
arg
end
end
def find_context
browser
end
def build_node(native_node, initial_cache = {})
::Capybara::Selenium::Node.new(self, native_node, initial_cache)
end
def bridge
browser.send(:bridge)
end
def specialize_driver
browser_type = browser.browser
Capybara::Selenium::Driver.specializations.select { |k, _v| k === browser_type }.each_value do |specialization| # rubocop:disable Style/CaseEquality
extend specialization
end
end
def setup_exit_handler
main = Process.pid
at_exit do
# Store the exit status of the test run since it goes away after calling the at_exit proc...
@exit_status = $ERROR_INFO.status if $ERROR_INFO.is_a?(SystemExit)
quit if Process.pid == main
exit @exit_status if @exit_status # Force exit with stored status
end
end
def reset_browser_state
clear_browser_state
@browser.navigate.to('about:blank')
end
def wait_for_empty_page(timer)
until find_xpath('/html/body/*').empty?
raise Capybara::ExpectationNotMet, 'Timed out waiting for Selenium session reset' if timer.expired?
sleep 0.01
# It has been observed that it is possible that asynchronous JS code in
# the application under test can navigate the browser away from about:blank
# if the timing is just right. Ensure we are still at about:blank...
@browser.navigate.to('about:blank') unless current_url == 'about:blank'
end
end
def accept_unhandled_reset_alert
@browser.switch_to.alert.accept
sleep 0.25 # allow time for the modal to be handled
rescue modal_error
# The alert is now gone.
# If navigation has not occurred attempt again and accept alert
# since FF may have dismissed the alert at first attempt.
navigate_with_accept('about:blank') if current_url != 'about:blank'
end
end
require 'capybara/selenium/driver_specializations/chrome_driver'
require 'capybara/selenium/driver_specializations/firefox_driver'
require 'capybara/selenium/driver_specializations/internet_explorer_driver'
require 'capybara/selenium/driver_specializations/safari_driver'
require 'capybara/selenium/driver_specializations/edge_driver'
| ruby | MIT | b3325b198464b806f07ec2011ceb532d6d5cf4ab | 2026-01-04T15:38:10.098638Z | false |
teamcapybara/capybara | https://github.com/teamcapybara/capybara/blob/b3325b198464b806f07ec2011ceb532d6d5cf4ab/lib/capybara/selenium/node.rb | lib/capybara/selenium/node.rb | # frozen_string_literal: true
# Selenium specific implementation of the Capybara::Driver::Node API
require 'capybara/selenium/extensions/find'
require 'capybara/selenium/extensions/scroll'
require 'capybara/node/whitespace_normalizer'
class Capybara::Selenium::Node < Capybara::Driver::Node
include Capybara::Node::WhitespaceNormalizer
include Capybara::Selenium::Find
include Capybara::Selenium::Scroll
def visible_text
raise NotImplementedError, 'Getting visible text is not currently supported directly on shadow roots' if shadow_root?
native.text
end
def all_text
text = driver.evaluate_script('arguments[0].textContent', self) || ''
normalize_spacing(text)
end
def [](name)
native.attribute(name.to_s)
rescue Selenium::WebDriver::Error::WebDriverError
nil
end
def value
if tag_name == 'select' && multiple?
native.find_elements(:css, 'option:checked').map { |el| el[:value] || el.text }
else
native[:value]
end
end
def style(styles)
styles.to_h { |style| [style, native.css_value(style)] }
end
##
#
# Set the value of the form element to the given value.
#
# @param [String] value The new value
# @param [Hash{}] options Driver specific options for how to set the value
# @option options [Symbol,Array] :clear (nil) The method used to clear the previous value <br/>
# nil => clear via javascript <br/>
# :none => append the new value to the existing value <br/>
# :backspace => send backspace keystrokes to clear the field <br/>
# Array => an array of keys to send before the value being set, e.g. [[:command, 'a'], :backspace]
# @option options [Boolean] :rapid (nil) Whether setting text inputs should use a faster "rapid" mode<br/>
# nil => Text inputs with length greater than 30 characters will be set using a faster driver script mode<br/>
# true => Rapid mode will be used regardless of input length<br/>
# false => Sends keys via conventional mode. This may be required to avoid losing key-presses if you have certain
# Javascript interactions on form inputs<br/>
def set(value, **options)
if value.is_a?(Array) && !multiple?
raise ArgumentError, "Value cannot be an Array when 'multiple' attribute is not present. Not a #{value.class}"
end
tag_name, type = attrs(:tagName, :type).map { |val| val&.downcase }
@tag_name ||= tag_name
case tag_name
when 'input'
case type
when 'radio'
click
when 'checkbox'
click if value ^ checked?
when 'file'
set_file(value)
when 'date'
set_date(value)
when 'time'
set_time(value)
when 'datetime-local'
set_datetime_local(value)
when 'color'
set_color(value)
when 'range'
set_range(value)
else
set_text(value, **options)
end
when 'textarea'
set_text(value, **options)
else
set_content_editable(value)
end
end
def select_option
click unless selected? || disabled?
end
def unselect_option
raise Capybara::UnselectNotAllowed, 'Cannot unselect option from single select box.' unless select_node.multiple?
click if selected?
end
def click(keys = [], **options)
click_options = ClickOptions.new(keys, options)
return native.click if click_options.empty?
perform_with_options(click_options) do |action|
target = click_options.coords? ? nil : native
if click_options.delay.zero?
action.click(target)
else
action.click_and_hold(target)
action_pause(action, click_options.delay)
action.release
end
end
rescue StandardError => e
if e.is_a?(::Selenium::WebDriver::Error::ElementClickInterceptedError) ||
e.message.include?('Other element would receive the click')
scroll_to_center
end
raise e
end
def right_click(keys = [], **options)
click_options = ClickOptions.new(keys, options)
perform_with_options(click_options) do |action|
target = click_options.coords? ? nil : native
if click_options.delay.zero?
action.context_click(target)
else
action.move_to(target) if target
action.pointer_down(:right).then do |act|
action_pause(act, click_options.delay)
end.pointer_up(:right)
end
end
end
def double_click(keys = [], **options)
click_options = ClickOptions.new(keys, options)
raise ArgumentError, "double_click doesn't support a delay option" unless click_options.delay.zero?
perform_with_options(click_options) do |action|
click_options.coords? ? action.double_click : action.double_click(native)
end
end
def send_keys(*args)
native.send_keys(*args)
end
def hover
scroll_if_needed { browser_action.move_to(native).perform }
end
def drag_to(element, drop_modifiers: [], **)
drop_modifiers = Array(drop_modifiers)
# Due to W3C spec compliance - The Actions API no longer scrolls to elements when necessary
# which means Seleniums `drag_and_drop` is now broken - do it manually
scroll_if_needed { browser_action.click_and_hold(native).perform }
# element.scroll_if_needed { browser_action.move_to(element.native).release.perform }
element.scroll_if_needed do
keys_down = modifiers_down(browser_action, drop_modifiers)
keys_up = modifiers_up(keys_down.move_to(element.native).release, drop_modifiers)
keys_up.perform
end
end
def drop(*_)
raise NotImplementedError, 'Out of browser drop emulation is not implemented for the current browser'
end
def tag_name
@tag_name ||=
if native.respond_to? :tag_name
native.tag_name.downcase
else
shadow_root? ? 'ShadowRoot' : 'Unknown'
end
end
def visible?; boolean_attr(native.displayed?); end
def readonly?; boolean_attr(self[:readonly]); end
def multiple?; boolean_attr(self[:multiple]); end
def selected?; boolean_attr(native.selected?); end
alias :checked? :selected?
def disabled?
return true unless native.enabled?
# WebDriver only defines `disabled?` for form controls but fieldset makes sense too
find_xpath('self::fieldset/ancestor-or-self::fieldset[@disabled]').any?
end
def content_editable?
native.attribute('isContentEditable') == 'true'
end
def path
driver.evaluate_script GET_XPATH_SCRIPT, self
end
def obscured?(x: nil, y: nil)
res = driver.evaluate_script(OBSCURED_OR_OFFSET_SCRIPT, self, x, y)
return true if res == true
driver.frame_obscured_at?(x: res['x'], y: res['y'])
end
def rect
native.rect
end
def shadow_root
root = native.shadow_root
root && build_node(native.shadow_root)
end
protected
def scroll_if_needed
yield
rescue ::Selenium::WebDriver::Error::MoveTargetOutOfBoundsError
scroll_to_center
yield
end
def scroll_to_center
script = <<-JS
try {
arguments[0].scrollIntoView({behavior: 'instant', block: 'center', inline: 'center'});
} catch(e) {
arguments[0].scrollIntoView(true);
}
JS
begin
driver.execute_script(script, self)
rescue StandardError
# Swallow error if scrollIntoView with options isn't supported
end
end
private
def sibling_index(parent, node, selector)
siblings = parent.find_xpath(selector)
case siblings.size
when 0
'[ERROR]' # IE doesn't support full XPath (namespace-uri, etc)
when 1
'' # index not necessary when only one matching element
else
idx = siblings.index(node)
# Element may not be found in the siblings if it has gone away
idx.nil? ? '[ERROR]' : "[#{idx + 1}]"
end
end
def boolean_attr(val)
val && (val != 'false')
end
# a reference to the select node if this is an option node
def select_node
find_xpath(XPath.ancestor(:select)[1]).first
end
def set_text(value, clear: nil, rapid: nil, **_unused)
value = value.to_s
if value.empty? && clear.nil?
native.clear
elsif clear == :backspace
# Clear field by sending the correct number of backspace keys.
backspaces = [:backspace] * self.value.to_s.length
send_keys(:end, *backspaces, value)
elsif clear.is_a? Array
send_keys(*clear, value)
else
driver.execute_script 'arguments[0].select()', self unless clear == :none
if rapid == true || ((value.length > auto_rapid_set_length) && rapid != false)
send_keys(value[0..3])
driver.execute_script RAPID_APPEND_TEXT, self, value[4...-3]
send_keys(value[-3..])
else
send_keys(value)
end
end
end
def auto_rapid_set_length
30
end
def perform_with_options(click_options, &block)
raise ArgumentError, 'A block must be provided' unless block
scroll_if_needed do
action_with_modifiers(click_options) do |action|
if block
yield action
else
click_options.coords? ? action.click : action.click(native)
end
end
end
end
def set_date(value) # rubocop:disable Naming/AccessorMethodName
value = SettableValue.new(value)
return set_text(value) unless value.dateable?
# TODO: this would be better if locale can be detected and correct keystrokes sent
update_value_js(value.to_date_str)
end
def set_time(value) # rubocop:disable Naming/AccessorMethodName
value = SettableValue.new(value)
return set_text(value) unless value.timeable?
# TODO: this would be better if locale can be detected and correct keystrokes sent
update_value_js(value.to_time_str)
end
def set_datetime_local(value) # rubocop:disable Naming/AccessorMethodName
value = SettableValue.new(value)
return set_text(value) unless value.timeable?
# TODO: this would be better if locale can be detected and correct keystrokes sent
update_value_js(value.to_datetime_str)
end
def set_color(value) # rubocop:disable Naming/AccessorMethodName
update_value_js(value)
end
def set_range(value) # rubocop:disable Naming/AccessorMethodName
update_value_js(value)
end
def update_value_js(value)
driver.execute_script(<<-JS, self, value)
if (arguments[0].readOnly) { return };
if (document.activeElement !== arguments[0]){
arguments[0].focus();
}
if (arguments[0].value != arguments[1]) {
arguments[0].value = arguments[1]
arguments[0].dispatchEvent(new InputEvent('input'));
arguments[0].dispatchEvent(new Event('change', { bubbles: true }));
}
JS
end
def set_file(value) # rubocop:disable Naming/AccessorMethodName
with_file_detector do
path_names = value.to_s.empty? ? [] : value
file_names = Array(path_names).map do |pn|
Pathname.new(pn).absolute? ? pn : File.expand_path(pn)
end.join("\n")
native.send_keys(file_names)
end
end
def with_file_detector
if driver.options[:browser] == :remote &&
bridge.respond_to?(:file_detector) &&
bridge.file_detector.nil?
begin
bridge.file_detector = lambda do |(fn, *)|
str = fn.to_s
str if File.exist?(str)
end
yield
ensure
bridge.file_detector = nil
end
else
yield
end
end
def set_content_editable(value) # rubocop:disable Naming/AccessorMethodName
# Ensure we are focused on the element
click
editable = driver.execute_script <<-JS, self
if (arguments[0].isContentEditable) {
var range = document.createRange();
var sel = window.getSelection();
arguments[0].focus();
range.selectNodeContents(arguments[0]);
sel.removeAllRanges();
sel.addRange(range);
return true;
}
return false;
JS
# The action api has a speed problem but both chrome and firefox 58 raise errors
# if we use the faster direct send_keys. For now just send_keys to the element
# we've already focused.
# native.send_keys(value.to_s)
browser_action.send_keys(value.to_s).perform if editable
end
def action_with_modifiers(click_options)
actions = browser_action.tap do |acts|
if click_options.coords?
if click_options.center_offset?
acts.move_to(native, *click_options.coords)
else
right_by, down_by = *click_options.coords
size = native.size
left_offset = (size[:width] / 2).to_i
top_offset = (size[:height] / 2).to_i
left = -left_offset + right_by
top = -top_offset + down_by
acts.move_to(native, left, top)
end
else
acts.move_to(native)
end
end
modifiers_down(actions, click_options.keys)
yield actions
modifiers_up(actions, click_options.keys)
actions.perform
ensure
act = browser_action
act.release_actions if act.respond_to?(:release_actions)
end
def modifiers_down(actions, keys)
each_key(keys) { |key| actions.key_down(key) }
actions
end
def modifiers_up(actions, keys)
each_key(keys) { |key| actions.key_up(key) }
actions
end
def browser
driver.browser
end
def bridge
browser.send(:bridge)
end
def browser_action
browser.action
end
def capabilities
browser.capabilities
end
def action_pause(action, duration)
action.pause(device: action.pointer_inputs.first, duration: duration)
end
def normalize_keys(keys)
keys.map do |key|
case key
when :ctrl then :control
when :command, :cmd then :meta
else
key
end
end
end
def each_key(keys, &block)
normalize_keys(keys).each(&block)
end
def find_context
native
end
def build_node(native_node, initial_cache = {})
self.class.new(driver, native_node, initial_cache)
end
def attrs(*attr_names)
return attr_names.map { |name| self[name.to_s] } if ENV['CAPYBARA_THOROUGH']
driver.evaluate_script <<~JS, self, attr_names.map(&:to_s)
(function(el, names){
return names.map(function(name){
return el[name]
});
})(arguments[0], arguments[1]);
JS
end
def native_id
# Selenium 3 -> 4 changed the return of ref
type_or_id, id = native.ref
id || type_or_id
end
def shadow_root?
defined?(::Selenium::WebDriver::ShadowRoot) && native.is_a?(::Selenium::WebDriver::ShadowRoot)
end
GET_XPATH_SCRIPT = <<~'JS'
(function(el, xml){
var xpath = '';
var pos, tempitem2;
if (el.getRootNode && el.getRootNode() instanceof ShadowRoot) {
return "(: Shadow DOM element - no XPath :)";
};
while(el !== xml.documentElement) {
pos = 0;
tempitem2 = el;
while(tempitem2) {
if (tempitem2.nodeType === 1 && tempitem2.nodeName === el.nodeName) { // If it is ELEMENT_NODE of the same name
pos += 1;
}
tempitem2 = tempitem2.previousSibling;
}
if (el.namespaceURI != xml.documentElement.namespaceURI) {
xpath = "*[local-name()='"+el.nodeName+"' and namespace-uri()='"+(el.namespaceURI===null?'':el.namespaceURI)+"']["+pos+']'+'/'+xpath;
} else {
xpath = el.nodeName.toUpperCase()+"["+pos+"]/"+xpath;
}
el = el.parentNode;
}
xpath = '/'+xml.documentElement.nodeName.toUpperCase()+'/'+xpath;
xpath = xpath.replace(/\/$/, '');
return xpath;
})(arguments[0], document)
JS
OBSCURED_OR_OFFSET_SCRIPT = <<~JS
(function(el, x, y) {
var box = el.getBoundingClientRect();
if (x == null) x = box.width/2;
if (y == null) y = box.height/2 ;
var px = box.left + x,
py = box.top + y,
e = document.elementFromPoint(px, py);
if (!el.contains(e))
return true;
return { x: px, y: py };
})(arguments[0], arguments[1], arguments[2])
JS
RAPID_APPEND_TEXT = <<~JS
(function(el, value) {
value = el.value + value;
if (el.maxLength && el.maxLength != -1){
value = value.slice(0, el.maxLength);
}
el.value = value;
})(arguments[0], arguments[1])
JS
# SettableValue encapsulates time/date field formatting
class SettableValue
attr_reader :value
def initialize(value)
@value = value
end
def to_s
value.to_s
end
def dateable?
!value.is_a?(String) && value.respond_to?(:to_date)
end
def to_date_str
value.to_date.iso8601
end
def timeable?
!value.is_a?(String) && value.respond_to?(:to_time)
end
def to_time_str
value.to_time.strftime('%H:%M')
end
def to_datetime_str
value.to_time.strftime('%Y-%m-%dT%H:%M')
end
end
private_constant :SettableValue
# ClickOptions encapsulates click option logic
class ClickOptions
attr_reader :keys, :options
def initialize(keys, options)
@keys = keys
@options = options
end
def coords?
options[:x] && options[:y]
end
def coords
[options[:x], options[:y]]
end
def center_offset?
options[:offset] == :center
end
def empty?
keys.empty? && !coords? && delay.zero?
end
def delay
options[:delay] || 0
end
end
private_constant :ClickOptions
end
| ruby | MIT | b3325b198464b806f07ec2011ceb532d6d5cf4ab | 2026-01-04T15:38:10.098638Z | false |
teamcapybara/capybara | https://github.com/teamcapybara/capybara/blob/b3325b198464b806f07ec2011ceb532d6d5cf4ab/lib/capybara/selenium/nodes/edge_node.rb | lib/capybara/selenium/nodes/edge_node.rb | # frozen_string_literal: true
require 'capybara/selenium/extensions/html5_drag'
class Capybara::Selenium::EdgeNode < Capybara::Selenium::Node
include Html5Drag
def set_text(value, clear: nil, **_unused)
return super unless chrome_edge?
super.tap do
# React doesn't see the chromedriver element clear
send_keys(:space, :backspace) if value.to_s.empty? && clear.nil?
end
end
def set_file(value) # rubocop:disable Naming/AccessorMethodName
# In Chrome 75+ files are appended (due to WebDriver spec - why?) so we have to clear here if its multiple and already set
if chrome_edge?
driver.execute_script(<<~JS, self)
if (arguments[0].multiple && arguments[0].files.length){
arguments[0].value = null;
}
JS
end
super
end
def drop(*args)
return super unless chrome_edge?
html5_drop(*args)
end
def click(*, **)
super
rescue Selenium::WebDriver::Error::InvalidArgumentError => e
tag_name, type = attrs(:tagName, :type).map { |val| val&.downcase }
if tag_name == 'input' && type == 'file'
raise Selenium::WebDriver::Error::InvalidArgumentError, "EdgeChrome can't click on file inputs.\n#{e.message}"
end
raise
end
def disabled?
return super unless chrome_edge?
driver.evaluate_script("arguments[0].matches(':disabled, select:disabled *')", self)
end
def select_option
return super unless chrome_edge?
# To optimize to only one check and then click
selected_or_disabled = driver.evaluate_script(<<~JS, self)
arguments[0].matches(':disabled, select:disabled *, :checked')
JS
click unless selected_or_disabled
end
def visible?
return super unless chrome_edge? && native_displayed?
begin
bridge.send(:execute, :is_element_displayed, id: native_id)
rescue Selenium::WebDriver::Error::UnknownCommandError
# If the is_element_displayed command is unknown, no point in trying again
driver.options[:native_displayed] = false
super
end
end
def send_keys(*args)
args.chunk { |inp| inp.is_a?(String) && inp.match?(/\p{Emoji Presentation}/) }
.each do |contains_emoji, inputs|
if contains_emoji
inputs.join.grapheme_clusters.chunk { |gc| gc.match?(/\p{Emoji Presentation}/) }
.each do |emoji, clusters|
if emoji
driver.send(:execute_cdp, 'Input.insertText', text: clusters.join)
else
super(clusters.join)
end
end
else
super(*inputs)
end
end
end
private
def browser_version
@browser_version ||= begin
caps = driver.browser.capabilities
(caps[:browser_version] || caps[:version]).to_f
end
end
def chrome_edge?
browser_version >= 75
end
def native_displayed?
(driver.options[:native_displayed] != false) &&
# chromedriver_supports_displayed_endpoint? &&
!ENV['DISABLE_CAPYBARA_SELENIUM_OPTIMIZATIONS']
end
end
| ruby | MIT | b3325b198464b806f07ec2011ceb532d6d5cf4ab | 2026-01-04T15:38:10.098638Z | false |
teamcapybara/capybara | https://github.com/teamcapybara/capybara/blob/b3325b198464b806f07ec2011ceb532d6d5cf4ab/lib/capybara/selenium/nodes/firefox_node.rb | lib/capybara/selenium/nodes/firefox_node.rb | # frozen_string_literal: true
require 'capybara/selenium/extensions/html5_drag'
require 'capybara/selenium/extensions/file_input_click_emulation'
class Capybara::Selenium::FirefoxNode < Capybara::Selenium::Node
include Html5Drag
include FileInputClickEmulation
def click(keys = [], **options)
super
rescue ::Selenium::WebDriver::Error::ElementNotInteractableError
if tag_name == 'tr'
warn 'You are attempting to click a table row which has issues in geckodriver/marionette - ' \
'see https://github.com/mozilla/geckodriver/issues/1228 - Your test should probably be ' \
'clicking on a table cell like a user would. Clicking the first cell in the row instead.'
return find_css('th:first-child,td:first-child')[0].click(keys, **options)
end
raise
end
def disabled?
driver.evaluate_script("arguments[0].matches(':disabled, select:disabled *')", self)
end
def set_file(value) # rubocop:disable Naming/AccessorMethodName
# By default files are appended so we have to clear here if its multiple and already set
driver.execute_script(<<~JS, self)
if (arguments[0].multiple && arguments[0].files.length){
arguments[0].value = null;
}
JS
return super if browser_version >= 62.0
# Workaround lack of support for multiple upload by uploading one at a time
path_names = value.to_s.empty? ? [] : Array(value)
if (fd = bridge.file_detector) && !driver.browser.respond_to?(:upload)
path_names.map! { |path| upload(fd.call([path])) || path }
end
path_names.each { |path| native.send_keys(path) }
end
def focused?
driver.evaluate_script('arguments[0] == document.activeElement', self)
end
def send_keys(*args)
# https://github.com/mozilla/geckodriver/issues/846
return super(*args.map { |arg| arg == :space ? ' ' : arg }) if args.none?(Array)
native.click unless focused?
_send_keys(args).perform
end
def drop(*args)
html5_drop(*args)
end
def hover
return super unless browser_version >= 65.0
# work around issue 2156 - https://github.com/teamcapybara/capybara/issues/2156
scroll_if_needed { browser_action.move_to(native, 0, 0).move_to(native).perform }
end
def select_option
# To optimize to only one check and then click
selected_or_disabled = driver.evaluate_script(<<~JS, self)
arguments[0].matches(':disabled, select:disabled *, :checked')
JS
click unless selected_or_disabled
end
def visible?
return super unless native_displayed?
begin
bridge.send(:execute, :is_element_displayed, id: native_id)
rescue Selenium::WebDriver::Error::UnknownCommandError
# If the is_element_displayed command is unknown, no point in trying again
driver.options[:native_displayed] = false
super
end
end
private
def native_displayed?
(driver.options[:native_displayed] != false) && !ENV['DISABLE_CAPYBARA_SELENIUM_OPTIMIZATIONS']
end
def perform_with_options(click_options)
# Firefox/marionette has an issue clicking with offset near viewport edge
# scroll element to middle just in case
scroll_to_center if click_options.coords?
super
end
def _send_keys(keys, actions = browser_action, down_keys = ModifierKeysStack.new)
case keys
when :control, :left_control, :right_control,
:alt, :left_alt, :right_alt,
:shift, :left_shift, :right_shift,
:meta, :left_meta, :right_meta,
:command
down_keys.press(keys)
actions.key_down(keys)
when String
# https://bugzilla.mozilla.org/show_bug.cgi?id=1405370
keys = keys.upcase if (browser_version < 64.0) && down_keys&.include?(:shift)
actions.send_keys(keys)
when Symbol
actions.send_keys(keys)
when Array
down_keys.push
keys.each { |sub_keys| _send_keys(sub_keys, actions, down_keys) }
down_keys.pop.reverse_each { |key| actions.key_up(key) }
else
raise ArgumentError, 'Unknown keys type'
end
actions
end
def upload(local_file)
return nil unless local_file
raise ArgumentError, "You may only upload files: #{local_file.inspect}" unless File.file?(local_file)
file = ::Selenium::WebDriver::Zipper.zip_file(local_file)
bridge.http.call(:post, "session/#{bridge.session_id}/file", file: file)['value']
end
def browser_version
driver.browser.capabilities[:browser_version].to_f
end
end
| ruby | MIT | b3325b198464b806f07ec2011ceb532d6d5cf4ab | 2026-01-04T15:38:10.098638Z | false |
teamcapybara/capybara | https://github.com/teamcapybara/capybara/blob/b3325b198464b806f07ec2011ceb532d6d5cf4ab/lib/capybara/selenium/nodes/safari_node.rb | lib/capybara/selenium/nodes/safari_node.rb | # frozen_string_literal: true
# require 'capybara/selenium/extensions/html5_drag'
require 'capybara/selenium/extensions/modifier_keys_stack'
class Capybara::Selenium::SafariNode < Capybara::Selenium::Node
# include Html5Drag
def click(keys = [], **options)
# driver.execute_script('arguments[0].scrollIntoViewIfNeeded({block: "center"})', self)
super
rescue ::Selenium::WebDriver::Error::ElementNotInteractableError
if tag_name == 'tr'
warn 'You are attempting to click a table row which has issues in safaridriver - ' \
'Your test should probably be clicking on a table cell like a user would. ' \
'Clicking the first cell in the row instead.'
return find_css('th:first-child,td:first-child')[0].click(keys, **options)
end
raise
rescue ::Selenium::WebDriver::Error::WebDriverError => e
raise unless e.instance_of? ::Selenium::WebDriver::Error::WebDriverError
# Safari doesn't return a specific error here - assume it's an ElementNotInteractableError
raise ::Selenium::WebDriver::Error::ElementNotInteractableError,
'Non distinct error raised in #click, translated to ElementNotInteractableError for retry'
end
def select_option
# To optimize to only one check and then click
selected_or_disabled = driver.execute_script(<<~JS, self)
arguments[0].closest('select').scrollIntoView();
return arguments[0].matches(':disabled, select:disabled *, :checked');
JS
click unless selected_or_disabled
end
def unselect_option
driver.execute_script("arguments[0].closest('select').scrollIntoView()", self)
super
end
def visible_text
return '' unless visible?
vis_text = driver.execute_script('return arguments[0].innerText', self)
vis_text.squeeze(' ')
.gsub(/[\ \n]*\n[\ \n]*/, "\n")
.gsub(/\A[[:space:]&&[^\u00a0]]+/, '')
.gsub(/[[:space:]&&[^\u00a0]]+\z/, '')
.tr("\u00a0", ' ')
end
def disabled?
driver.evaluate_script("arguments[0].matches(':disabled, select:disabled *')", self)
end
def set_file(value) # rubocop:disable Naming/AccessorMethodName
# By default files are appended so we have to clear here if its multiple and already set
native.clear if multiple? && driver.evaluate_script('arguments[0].files', self).any?
super
end
def send_keys(*args)
if args.none? { |arg| arg.is_a?(Array) || (arg.is_a?(Symbol) && MODIFIER_KEYS.include?(arg)) }
return super(*args.map { |arg| arg == :space ? ' ' : arg })
end
native.click
_send_keys(args).perform
end
def set_text(value, clear: nil, **_unused)
value = value.to_s
if clear == :backspace
# Clear field by sending the correct number of backspace keys.
backspaces = [:backspace] * self.value.to_s.length
send_keys([:control, 'e'], *backspaces, value)
else
super.tap do
# React doesn't see the safaridriver element clear
send_keys(:space, :backspace) if value.to_s.empty? && clear.nil?
end
end
end
def hover
# Workaround issue where hover would sometimes fail - possibly due to mouse not having moved
scroll_if_needed { browser_action.move_to(native, 0, 0).move_to(native).perform }
end
private
def _send_keys(keys, actions = browser_action, down_keys = ModifierKeysStack.new)
case keys
when *MODIFIER_KEYS
down_keys.press(keys)
actions.key_down(keys)
when String
keys = keys.upcase if down_keys&.include?(:shift)
actions.send_keys(keys)
when Symbol
actions.send_keys(keys)
when Array
down_keys.push
keys.each { |sub_keys| _send_keys(sub_keys, actions, down_keys) }
down_keys.pop.reverse_each { |key| actions.key_up(key) }
else
raise ArgumentError, 'Unknown keys type'
end
actions
end
MODIFIER_KEYS = %i[control left_control right_control
alt left_alt right_alt
shift left_shift right_shift
meta left_meta right_meta
command].freeze
end
| ruby | MIT | b3325b198464b806f07ec2011ceb532d6d5cf4ab | 2026-01-04T15:38:10.098638Z | false |
teamcapybara/capybara | https://github.com/teamcapybara/capybara/blob/b3325b198464b806f07ec2011ceb532d6d5cf4ab/lib/capybara/selenium/nodes/ie_node.rb | lib/capybara/selenium/nodes/ie_node.rb | # frozen_string_literal: true
require 'capybara/selenium/extensions/html5_drag'
class Capybara::Selenium::IENode < Capybara::Selenium::Node
def disabled?
# super
# optimize to one script call
driver.evaluate_script <<~JS.delete("\n"), self
arguments[0].msMatchesSelector('
:disabled,
select:disabled *,
optgroup:disabled *,
fieldset[disabled],
fieldset[disabled] > *:not(legend),
fieldset[disabled] > *:not(legend) *,
fieldset[disabled] > legend:nth-of-type(n+2),
fieldset[disabled] > legend:nth-of-type(n+2) *
')
JS
end
end
| ruby | MIT | b3325b198464b806f07ec2011ceb532d6d5cf4ab | 2026-01-04T15:38:10.098638Z | false |
teamcapybara/capybara | https://github.com/teamcapybara/capybara/blob/b3325b198464b806f07ec2011ceb532d6d5cf4ab/lib/capybara/selenium/nodes/chrome_node.rb | lib/capybara/selenium/nodes/chrome_node.rb | # frozen_string_literal: true
require 'capybara/selenium/extensions/html5_drag'
require 'capybara/selenium/extensions/file_input_click_emulation'
class Capybara::Selenium::ChromeNode < Capybara::Selenium::Node
include Html5Drag
include FileInputClickEmulation
def set_text(value, clear: nil, **_unused)
super.tap do
# React doesn't see the chromedriver element clear
send_keys(:space, :backspace) if value.to_s.empty? && clear.nil?
end
end
def set_file(value) # rubocop:disable Naming/AccessorMethodName
# In Chrome 75+ files are appended (due to WebDriver spec - why?) so we have to clear here if its multiple and already set
if browser_version >= 75.0
driver.execute_script(<<~JS, self)
if (arguments[0].multiple && arguments[0].files.length){
arguments[0].value = null;
}
JS
end
super
end
def drop(*args)
html5_drop(*args)
end
def click(*, **)
super
rescue ::Selenium::WebDriver::Error::ElementClickInterceptedError
raise
rescue ::Selenium::WebDriver::Error::WebDriverError => e
# chromedriver 74 (at least on mac) raises the wrong error for this
if e.message.include?('element click intercepted')
raise ::Selenium::WebDriver::Error::ElementClickInterceptedError, e.message
end
raise
end
def disabled?
driver.evaluate_script("arguments[0].matches(':disabled, select:disabled *')", self)
end
def select_option
# To optimize to only one check and then click
selected_or_disabled = driver.evaluate_script(<<~JS, self)
arguments[0].matches(':disabled, select:disabled *, :checked')
JS
click unless selected_or_disabled
end
def visible?
return super unless native_displayed?
begin
bridge.send(:execute, :is_element_displayed, id: native_id)
rescue Selenium::WebDriver::Error::UnknownCommandError
# If the is_element_displayed command is unknown, no point in trying again
driver.options[:native_displayed] = false
super
end
end
def send_keys(*args)
args.chunk { |inp| inp.is_a?(String) && inp.match?(/\p{Emoji Presentation}/) }
.each do |contains_emoji, inputs|
if contains_emoji
inputs.join.grapheme_clusters.chunk { |gc| gc.match?(/\p{Emoji Presentation}/) }
.each do |emoji, clusters|
if emoji
driver.send(:execute_cdp, 'Input.insertText', text: clusters.join)
else
super(clusters.join)
end
end
else
super(*inputs)
end
end
end
protected
def catch_error?(error, errors = nil)
# Selenium::WebDriver::Error::UnknownError:
# unknown error: unhandled inspector error: {"code":-32000,"message":"Node with given id does not belong to the document"}
super ||
(error.is_a?(Selenium::WebDriver::Error::UnknownError) &&
error.message.include?('Node with given id does not belong to the document'))
end
private
def perform_legacy_drag(element, drop_modifiers)
return super if chromedriver_fixed_actions_key_state? || element.obscured?
raise ArgumentError, 'Modifier keys are not supported while dragging in this version of Chrome.' unless drop_modifiers.empty?
# W3C Chrome/chromedriver < 77 doesn't maintain mouse button state across actions API performs
# https://bugs.chromium.org/p/chromedriver/issues/detail?id=2981
browser_action.release.perform
browser_action.click_and_hold(native).move_to(element.native).release.perform
end
def browser_version(to_float: true)
caps = capabilities
ver = caps[:browser_version] || caps[:version]
ver = ver.to_f if to_float
ver
end
def chromedriver_fixed_actions_key_state?
Gem::Requirement.new('>= 76.0.3809.68').satisfied_by?(chromedriver_version)
end
def chromedriver_supports_displayed_endpoint?
Gem::Requirement.new('>= 76.0.3809.25').satisfied_by?(chromedriver_version)
end
def chromedriver_version
Gem::Version.new(capabilities['chrome']['chromedriverVersion'].split(' ')[0]) # rubocop:disable Style/RedundantArgument
end
def native_displayed?
(driver.options[:native_displayed] != false) &&
chromedriver_supports_displayed_endpoint? &&
!ENV['DISABLE_CAPYBARA_SELENIUM_OPTIMIZATIONS']
end
end
| ruby | MIT | b3325b198464b806f07ec2011ceb532d6d5cf4ab | 2026-01-04T15:38:10.098638Z | false |
teamcapybara/capybara | https://github.com/teamcapybara/capybara/blob/b3325b198464b806f07ec2011ceb532d6d5cf4ab/lib/capybara/selenium/extensions/file_input_click_emulation.rb | lib/capybara/selenium/extensions/file_input_click_emulation.rb | # frozen_string_literal: true
class Capybara::Selenium::Node
module FileInputClickEmulation
def click(keys = [], **options)
super
rescue Selenium::WebDriver::Error::InvalidArgumentError
return emulate_click if attaching_file? && visible_file_field?
raise
end
private
def visible_file_field?
(attrs(:tagName, :type).map { |val| val&.downcase } == %w[input file]) && visible?
end
def attaching_file?
caller_locations.any? { |cl| cl.base_label == 'attach_file' }
end
def emulate_click
driver.execute_script(<<~JS, self)
arguments[0].dispatchEvent(
new MouseEvent('click', {
view: window,
bubbles: true,
cancelable: true
}));
JS
end
end
end
| ruby | MIT | b3325b198464b806f07ec2011ceb532d6d5cf4ab | 2026-01-04T15:38:10.098638Z | false |
teamcapybara/capybara | https://github.com/teamcapybara/capybara/blob/b3325b198464b806f07ec2011ceb532d6d5cf4ab/lib/capybara/selenium/extensions/find.rb | lib/capybara/selenium/extensions/find.rb | # frozen_string_literal: true
module Capybara
module Selenium
module Find
def find_xpath(selector, uses_visibility: false, styles: nil, position: false, **_options)
find_by(:xpath, selector, uses_visibility: uses_visibility, texts: [], styles: styles, position: position)
end
def find_css(selector, uses_visibility: false, texts: [], styles: nil, position: false, **_options)
find_by(:css, selector, uses_visibility: uses_visibility, texts: texts, styles: styles, position: position)
end
private
def find_by(format, selector, uses_visibility:, texts:, styles:, position:)
els = find_context.find_elements(format, selector)
hints = []
if (els.size > 2) && !ENV['DISABLE_CAPYBARA_SELENIUM_OPTIMIZATIONS']
els = filter_by_text(els, texts) unless texts.empty?
hints = begin
gather_hints(els, uses_visibility: uses_visibility, styles: styles, position: position)
rescue Selenium::WebDriver::Error::JavascriptError
# Unclear how this can happen but issue #2729 indicates it can
[]
end
end
els.map.with_index { |el, idx| build_node(el, hints[idx] || {}) }
end
def gather_hints(elements, uses_visibility:, styles:, position:)
hints_js, functions = build_hints_js(uses_visibility, styles, position)
return [] unless functions.any?
(es_context.execute_script(hints_js, elements) || []).map! do |results|
hint = {}
hint[:style] = results.pop if functions.include?(:style_func)
hint[:position] = results.pop if functions.include?(:position_func)
hint[:visible] = results.pop if functions.include?(:vis_func)
hint
end
rescue ::Selenium::WebDriver::Error::StaleElementReferenceError,
::Capybara::NotSupportedByDriverError
# warn 'Unexpected Stale Element Error - skipping optimization'
[]
end
def filter_by_text(elements, texts)
es_context.execute_script <<~JS, elements, texts
var texts = arguments[1];
return arguments[0].filter(function(el){
var content = el.textContent.toLowerCase();
return texts.every(function(txt){ return content.indexOf(txt.toLowerCase()) != -1 });
})
JS
end
def build_hints_js(uses_visibility, styles, position)
functions = []
hints_js = +''
if uses_visibility && !is_displayed_atom.empty?
hints_js << <<~VISIBILITY_JS
var vis_func = #{is_displayed_atom};
VISIBILITY_JS
functions << :vis_func
end
if position
hints_js << <<~POSITION_JS
var position_func = function(el){
return el.getBoundingClientRect();
};
POSITION_JS
functions << :position_func
end
if styles.is_a? Hash
hints_js << <<~STYLE_JS
var style_func = function(el){
var el_styles = window.getComputedStyle(el);
return #{styles.keys.map(&:to_s)}.reduce(function(res, style){
res[style] = el_styles[style];
return res;
}, {});
};
STYLE_JS
functions << :style_func
end
hints_js << <<~EACH_JS
return arguments[0].map(function(el){
return [#{functions.join(',')}].map(function(fn){ return fn.call(null, el) });
});
EACH_JS
[hints_js, functions]
end
def es_context
respond_to?(:execute_script) ? self : driver
end
def is_displayed_atom # rubocop:disable Naming/PredicatePrefix
@@is_displayed_atom ||= begin # rubocop:disable Style/ClassVars
browser.send(:bridge).send(:read_atom, 'isDisplayed')
rescue StandardError
# If the atom doesn't exist or other error
''
end
end
end
end
end
| ruby | MIT | b3325b198464b806f07ec2011ceb532d6d5cf4ab | 2026-01-04T15:38:10.098638Z | false |
teamcapybara/capybara | https://github.com/teamcapybara/capybara/blob/b3325b198464b806f07ec2011ceb532d6d5cf4ab/lib/capybara/selenium/extensions/modifier_keys_stack.rb | lib/capybara/selenium/extensions/modifier_keys_stack.rb | # frozen_string_literal: true
class Capybara::Selenium::Node
#
# @api private
#
class ModifierKeysStack
def initialize
@stack = []
end
def include?(key)
@stack.flatten.include?(key)
end
def press(key)
@stack.last.push(key)
end
def push
@stack.push []
end
def pop
@stack.pop
end
end
end
| ruby | MIT | b3325b198464b806f07ec2011ceb532d6d5cf4ab | 2026-01-04T15:38:10.098638Z | false |
teamcapybara/capybara | https://github.com/teamcapybara/capybara/blob/b3325b198464b806f07ec2011ceb532d6d5cf4ab/lib/capybara/selenium/extensions/html5_drag.rb | lib/capybara/selenium/extensions/html5_drag.rb | # frozen_string_literal: true
class Capybara::Selenium::Node
module Html5Drag
# Implement methods to emulate HTML5 drag and drop
def drag_to(element, html5: nil, delay: 0.05, drop_modifiers: [])
drop_modifiers = Array(drop_modifiers)
driver.execute_script MOUSEDOWN_TRACKER
scroll_if_needed { browser_action.click_and_hold(native).perform }
html5 = !driver.evaluate_script(LEGACY_DRAG_CHECK, self) if html5.nil?
if html5
perform_html5_drag(element, delay, drop_modifiers)
else
perform_legacy_drag(element, drop_modifiers)
end
end
private
def perform_legacy_drag(element, drop_modifiers)
element.scroll_if_needed do
# browser_action.move_to(element.native).release.perform
keys_down = modifiers_down(browser_action, drop_modifiers)
keys_up = modifiers_up(keys_down.move_to(element.native).release, drop_modifiers)
keys_up.perform
end
end
def perform_html5_drag(element, delay, drop_modifiers)
driver.evaluate_async_script HTML5_DRAG_DROP_SCRIPT, self, element, delay * 1000, normalize_keys(drop_modifiers)
browser_action.release.perform
end
def html5_drop(*args)
if args[0].is_a? String
input = driver.evaluate_script ATTACH_FILE
input.set_file(args)
driver.execute_script DROP_FILE, self, input
else
items = args.flat_map do |arg|
arg.map { |(type, data)| { type: type, data: data } }
end
driver.execute_script DROP_STRING, items, self
end
end
DROP_STRING = <<~JS
var strings = arguments[0],
el = arguments[1],
dt = new DataTransfer(),
opts = { cancelable: true, bubbles: true, dataTransfer: dt };
for (var i=0; i < strings.length; i++){
if (dt.items) {
dt.items.add(strings[i]['data'], strings[i]['type']);
} else {
dt.setData(strings[i]['type'], strings[i]['data']);
}
}
var dropEvent = new DragEvent('drop', opts);
el.dispatchEvent(dropEvent);
JS
DROP_FILE = <<~JS
var el = arguments[0],
input = arguments[1],
files = input.files,
dt = new DataTransfer(),
opts = { cancelable: true, bubbles: true, dataTransfer: dt };
input.parentElement.removeChild(input);
if (dt.items){
for (var i=0; i<files.length; i++){
dt.items.add(files[i]);
}
} else {
Object.defineProperty(dt, "files", {
value: files,
writable: false
});
}
var dropEvent = new DragEvent('drop', opts);
el.dispatchEvent(dropEvent);
JS
ATTACH_FILE = <<~JS
(function(){
var input = document.createElement('INPUT');
input.type = "file";
input.id = "_capybara_drop_file";
input.multiple = true;
document.body.appendChild(input);
return input;
})()
JS
MOUSEDOWN_TRACKER = <<~JS
window.capybara_mousedown_prevented = null;
document.addEventListener('mousedown', ev => {
window.capybara_mousedown_prevented = ev.defaultPrevented;
}, { once: true, passive: true })
JS
LEGACY_DRAG_CHECK = <<~JS
(function(el){
if ([true, null].indexOf(window.capybara_mousedown_prevented) >= 0){
return true;
}
do {
if (el.draggable) return false;
} while (el = el.parentElement );
return true;
})(arguments[0])
JS
HTML5_DRAG_DROP_SCRIPT = <<~JS
function rectCenter(rect){
return new DOMPoint(
(rect.left + rect.right)/2,
(rect.top + rect.bottom)/2
);
}
function pointOnRect(pt, rect) {
var rectPt = rectCenter(rect);
var slope = (rectPt.y - pt.y) / (rectPt.x - pt.x);
if (pt.x <= rectPt.x) { // left side
var minXy = slope * (rect.left - pt.x) + pt.y;
if (rect.top <= minXy && minXy <= rect.bottom)
return new DOMPoint(rect.left, minXy);
}
if (pt.x >= rectPt.x) { // right side
var maxXy = slope * (rect.right - pt.x) + pt.y;
if (rect.top <= maxXy && maxXy <= rect.bottom)
return new DOMPoint(rect.right, maxXy);
}
if (pt.y <= rectPt.y) { // top side
var minYx = (rectPt.top - pt.y) / slope + pt.x;
if (rect.left <= minYx && minYx <= rect.right)
return new DOMPoint(minYx, rect.top);
}
if (pt.y >= rectPt.y) { // bottom side
var maxYx = (rect.bottom - pt.y) / slope + pt.x;
if (rect.left <= maxYx && maxYx <= rect.right)
return new DOMPoint(maxYx, rect.bottom);
}
return new DOMPoint(pt.x,pt.y);
}
function dragEnterTarget() {
target.scrollIntoView({behavior: 'instant', block: 'center', inline: 'center'});
var targetRect = target.getBoundingClientRect();
var sourceCenter = rectCenter(source.getBoundingClientRect());
for (var i = 0; i < drop_modifier_keys.length; i++) {
key = drop_modifier_keys[i];
if (key == "control"){
key = "ctrl"
}
opts[key + 'Key'] = true;
}
var dragEnterEvent = new DragEvent('dragenter', opts);
target.dispatchEvent(dragEnterEvent);
// fire 2 dragover events to simulate dragging with a direction
var entryPoint = pointOnRect(sourceCenter, targetRect)
var dragOverOpts = Object.assign({clientX: entryPoint.x, clientY: entryPoint.y}, opts);
var dragOverEvent = new DragEvent('dragover', dragOverOpts);
target.dispatchEvent(dragOverEvent);
window.setTimeout(dragOnTarget, step_delay);
}
function dragOnTarget() {
var targetCenter = rectCenter(target.getBoundingClientRect());
var dragOverOpts = Object.assign({clientX: targetCenter.x, clientY: targetCenter.y}, opts);
var dragOverEvent = new DragEvent('dragover', dragOverOpts);
target.dispatchEvent(dragOverEvent);
window.setTimeout(dragLeave, step_delay, dragOverEvent.defaultPrevented, dragOverOpts);
}
function dragLeave(drop, dragOverOpts) {
var dragLeaveOptions = Object.assign({}, opts, dragOverOpts);
var dragLeaveEvent = new DragEvent('dragleave', dragLeaveOptions);
target.dispatchEvent(dragLeaveEvent);
if (drop) {
var dropEvent = new DragEvent('drop', dragLeaveOptions);
target.dispatchEvent(dropEvent);
}
var dragEndEvent = new DragEvent('dragend', dragLeaveOptions);
source.dispatchEvent(dragEndEvent);
callback.call(true);
}
var source = arguments[0],
target = arguments[1],
step_delay = arguments[2],
drop_modifier_keys = arguments[3],
callback = arguments[4];
var dt = new DataTransfer();
var opts = { cancelable: true, bubbles: true, dataTransfer: dt };
while (source && !source.draggable) {
source = source.parentElement;
}
if (source.tagName == 'A'){
dt.setData('text/uri-list', source.href);
dt.setData('text', source.href);
}
if (source.tagName == 'IMG'){
dt.setData('text/uri-list', source.src);
dt.setData('text', source.src);
}
var dragEvent = new DragEvent('dragstart', opts);
source.dispatchEvent(dragEvent);
window.setTimeout(dragEnterTarget, step_delay);
JS
end
end
| ruby | MIT | b3325b198464b806f07ec2011ceb532d6d5cf4ab | 2026-01-04T15:38:10.098638Z | false |
teamcapybara/capybara | https://github.com/teamcapybara/capybara/blob/b3325b198464b806f07ec2011ceb532d6d5cf4ab/lib/capybara/selenium/extensions/scroll.rb | lib/capybara/selenium/extensions/scroll.rb | # frozen_string_literal: true
module Capybara
module Selenium
module Scroll
def scroll_by(x, y)
driver.execute_script <<~JS, self, x, y
var el = arguments[0];
if (el.scrollBy){
el.scrollBy(arguments[1], arguments[2]);
} else {
el.scrollTop = el.scrollTop + arguments[2];
el.scrollLeft = el.scrollLeft + arguments[1];
}
JS
end
def scroll_to(element, location, position = nil)
# location, element = element, nil if element.is_a? Symbol
if element.is_a? Capybara::Selenium::Node
scroll_element_to_location(element, location)
elsif location.is_a? Symbol
scroll_to_location(location)
else
scroll_to_coords(*position)
end
self
end
private
def scroll_element_to_location(element, location)
scroll_opts = case location
when :top
'true'
when :bottom
'false'
when :center
"{behavior: 'instant', block: 'center'}"
else
raise ArgumentError, "Invalid scroll_to location: #{location}"
end
driver.execute_script <<~JS, element
arguments[0].scrollIntoView(#{scroll_opts})
JS
end
SCROLL_POSITIONS = {
top: '0',
bottom: 'arguments[0].scrollHeight',
center: '(arguments[0].scrollHeight - arguments[0].clientHeight)/2'
}.freeze
def scroll_to_location(location)
driver.execute_script <<~JS, self
if (arguments[0].scrollTo){
arguments[0].scrollTo(0, #{SCROLL_POSITIONS[location]});
} else {
arguments[0].scrollTop = #{SCROLL_POSITIONS[location]};
}
JS
end
def scroll_to_coords(x, y)
driver.execute_script <<~JS, self, x, y
if (arguments[0].scrollTo){
arguments[0].scrollTo(arguments[1], arguments[2]);
} else {
arguments[0].scrollTop = arguments[2];
arguments[0].scrollLeft = arguments[1];
}
JS
end
end
end
end
| ruby | MIT | b3325b198464b806f07ec2011ceb532d6d5cf4ab | 2026-01-04T15:38:10.098638Z | false |
teamcapybara/capybara | https://github.com/teamcapybara/capybara/blob/b3325b198464b806f07ec2011ceb532d6d5cf4ab/lib/capybara/selenium/driver_specializations/internet_explorer_driver.rb | lib/capybara/selenium/driver_specializations/internet_explorer_driver.rb | # frozen_string_literal: true
require 'capybara/selenium/nodes/ie_node'
module Capybara::Selenium::Driver::InternetExplorerDriver
def switch_to_frame(frame)
return super unless frame == :parent
# iedriverserver has an issue if the current frame is removed from within it
# so we have to move to the default_content and iterate back through the frames
handles = @frame_handles[current_window_handle]
browser.switch_to.default_content
handles.tap(&:pop).each { |fh| browser.switch_to.frame(fh.native) }
end
private
def build_node(native_node, initial_cache = {})
::Capybara::Selenium::IENode.new(self, native_node, initial_cache)
end
end
module Capybara::Selenium
Driver.register_specialization :ie, Driver::InternetExplorerDriver
Driver.register_specialization :internet_explorer, Driver::InternetExplorerDriver
end
| ruby | MIT | b3325b198464b806f07ec2011ceb532d6d5cf4ab | 2026-01-04T15:38:10.098638Z | false |
teamcapybara/capybara | https://github.com/teamcapybara/capybara/blob/b3325b198464b806f07ec2011ceb532d6d5cf4ab/lib/capybara/selenium/driver_specializations/safari_driver.rb | lib/capybara/selenium/driver_specializations/safari_driver.rb | # frozen_string_literal: true
require 'capybara/selenium/nodes/safari_node'
module Capybara::Selenium::Driver::SafariDriver
def switch_to_frame(frame)
return super unless frame == :parent
# safaridriver/safari has an issue where switch_to_frame(:parent)
# behaves like switch_to_frame(:top)
handles = @frame_handles[current_window_handle]
browser.switch_to.default_content
handles.tap(&:pop).each { |fh| browser.switch_to.frame(fh.native) }
end
private
def build_node(native_node, initial_cache = {})
::Capybara::Selenium::SafariNode.new(self, native_node, initial_cache)
end
end
Capybara::Selenium::Driver.register_specialization(/^(safari|Safari_Technology_Preview)$/,
Capybara::Selenium::Driver::SafariDriver)
| ruby | MIT | b3325b198464b806f07ec2011ceb532d6d5cf4ab | 2026-01-04T15:38:10.098638Z | false |
teamcapybara/capybara | https://github.com/teamcapybara/capybara/blob/b3325b198464b806f07ec2011ceb532d6d5cf4ab/lib/capybara/selenium/driver_specializations/chrome_driver.rb | lib/capybara/selenium/driver_specializations/chrome_driver.rb | # frozen_string_literal: true
require 'capybara/selenium/nodes/chrome_node'
require 'capybara/selenium/patches/logs'
module Capybara::Selenium::Driver::ChromeDriver
def self.extended(base)
bridge = base.send(:bridge)
bridge.extend Capybara::Selenium::ChromeLogs unless bridge.respond_to?(:log)
bridge.extend Capybara::Selenium::IsDisplayed unless bridge.send(:commands, :is_element_displayed)
base.options[:native_displayed] = false if base.options[:native_displayed].nil?
end
def fullscreen_window(handle)
within_given_window(handle) do
super
rescue NoMethodError => e
raise unless e.message.include?('full_screen_window')
result = bridge.http.call(:post, "session/#{bridge.session_id}/window/fullscreen", {})
result['value']
end
end
def resize_window_to(handle, width, height)
super
rescue Selenium::WebDriver::Error::UnknownError => e
raise unless e.message.include?('failed to change window state')
# Chromedriver doesn't wait long enough for state to change when coming out of fullscreen
# and raises unnecessary error. Wait a bit and try again.
sleep 0.25
super
end
def reset!
# Use instance variable directly so we avoid starting the browser just to reset the session
return unless @browser
switch_to_window(window_handles.first)
window_handles.slice(1..).each { |win| close_window(win) }
return super if chromedriver_version < 73
timer = Capybara::Helpers.timer(expire_in: 10)
begin
clear_storage unless uniform_storage_clear?
@browser.navigate.to('about:blank')
wait_for_empty_page(timer)
rescue *unhandled_alert_errors
accept_unhandled_reset_alert
retry
end
execute_cdp('Storage.clearDataForOrigin', origin: '*', storageTypes: storage_types_to_clear)
end
private
def storage_types_to_clear
types = ['cookies']
types << 'local_storage' if clear_all_storage?
types.join(',')
end
def clear_all_storage?
storage_clears.none? false
end
def uniform_storage_clear?
storage_clears.uniq { |s| s == false }.length <= 1
end
def storage_clears
options.values_at(:clear_session_storage, :clear_local_storage)
end
def clear_storage
# Chrome errors if attempt to clear storage on about:blank
# In W3C mode it crashes chromedriver
url = current_url
super unless url.nil? || url.start_with?('about:')
end
def delete_all_cookies
execute_cdp('Network.clearBrowserCookies')
rescue *cdp_unsupported_errors
# If the CDP clear isn't supported do original limited clear
super
end
def cdp_unsupported_errors
@cdp_unsupported_errors ||= [Selenium::WebDriver::Error::WebDriverError]
end
def execute_cdp(cmd, params = {})
if browser.respond_to? :execute_cdp
browser.execute_cdp(cmd, **params)
else
args = { cmd: cmd, params: params }
result = bridge.http.call(:post, "session/#{bridge.session_id}/goog/cdp/execute", args)
result['value']
end
end
def build_node(native_node, initial_cache = {})
::Capybara::Selenium::ChromeNode.new(self, native_node, initial_cache)
end
def chromedriver_version
@chromedriver_version ||= begin
caps = browser.capabilities
caps['chrome']&.fetch('chromedriverVersion', nil).to_f
end
end
end
Capybara::Selenium::Driver.register_specialization :chrome, Capybara::Selenium::Driver::ChromeDriver
| ruby | MIT | b3325b198464b806f07ec2011ceb532d6d5cf4ab | 2026-01-04T15:38:10.098638Z | false |
teamcapybara/capybara | https://github.com/teamcapybara/capybara/blob/b3325b198464b806f07ec2011ceb532d6d5cf4ab/lib/capybara/selenium/driver_specializations/firefox_driver.rb | lib/capybara/selenium/driver_specializations/firefox_driver.rb | # frozen_string_literal: true
require 'capybara/selenium/nodes/firefox_node'
module Capybara::Selenium::Driver::FirefoxDriver
def self.extended(driver)
driver.extend Capybara::Selenium::Driver::W3CFirefoxDriver
bridge = driver.send(:bridge)
bridge.extend Capybara::Selenium::IsDisplayed unless bridge.send(:commands, :is_element_displayed)
end
end
module Capybara::Selenium::Driver::W3CFirefoxDriver
class << self
def extended(driver)
require 'capybara/selenium/patches/pause_duration_fix' if pause_broken?(driver.browser)
driver.options[:native_displayed] = false if driver.options[:native_displayed].nil?
end
def pause_broken?(sel_driver)
sel_driver.capabilities['moz:geckodriverVersion']&.start_with?('0.22.')
end
end
def resize_window_to(handle, width, height)
within_given_window(handle) do
# Don't set the size if already set - See https://github.com/mozilla/geckodriver/issues/643
if window_size(handle) == [width, height]
{}
else
super
end
end
end
def reset!
# Use instance variable directly so we avoid starting the browser just to reset the session
return unless @browser
if browser_version >= 68
begin
# Firefox 68 hangs if we try to switch windows while a modal is visible
browser.switch_to.alert&.dismiss
rescue Selenium::WebDriver::Error::NoSuchAlertError
# Swallow
end
end
switch_to_window(window_handles.first)
window_handles.slice(1..).each { |win| close_window(win) }
super
end
def refresh
# Accept any "will repost content" confirmation that occurs
accept_modal :confirm, wait: 0.1 do
super
end
rescue Capybara::ModalNotFound
# No modal was opened - page has refreshed - ignore
end
def switch_to_frame(frame)
return super unless frame == :parent
# geckodriver/firefox has an issue if the current frame is removed from within it
# so we have to move to the default_content and iterate back through the frames
handles = @frame_handles[current_window_handle]
browser.switch_to.default_content
handles.tap(&:pop).each { |fh| browser.switch_to.frame(fh.native) }
end
private
def build_node(native_node, initial_cache = {})
::Capybara::Selenium::FirefoxNode.new(self, native_node, initial_cache)
end
def browser_version
browser.capabilities[:browser_version].to_f
end
end
Capybara::Selenium::Driver.register_specialization :firefox, Capybara::Selenium::Driver::FirefoxDriver
| ruby | MIT | b3325b198464b806f07ec2011ceb532d6d5cf4ab | 2026-01-04T15:38:10.098638Z | false |
teamcapybara/capybara | https://github.com/teamcapybara/capybara/blob/b3325b198464b806f07ec2011ceb532d6d5cf4ab/lib/capybara/selenium/driver_specializations/edge_driver.rb | lib/capybara/selenium/driver_specializations/edge_driver.rb | # frozen_string_literal: true
require 'capybara/selenium/nodes/edge_node'
module Capybara::Selenium::Driver::EdgeDriver
def self.extended(base)
bridge = base.send(:bridge)
bridge.extend Capybara::Selenium::IsDisplayed unless bridge.send(:commands, :is_element_displayed)
base.options[:native_displayed] = false if base.options[:native_displayed].nil?
end
def fullscreen_window(handle)
return super if edgedriver_version < 75
within_given_window(handle) do
super
rescue NoMethodError => e
raise unless e.message.include?('full_screen_window')
result = bridge.http.call(:post, "session/#{bridge.session_id}/window/fullscreen", {})
result['value']
end
end
def resize_window_to(handle, width, height)
super
rescue Selenium::WebDriver::Error::UnknownError => e
raise unless e.message.include?('failed to change window state')
# Chromedriver doesn't wait long enough for state to change when coming out of fullscreen
# and raises unnecessary error. Wait a bit and try again.
sleep 0.25
super
end
def reset!
return super if edgedriver_version < 75
# Use instance variable directly so we avoid starting the browser just to reset the session
return unless @browser
switch_to_window(window_handles.first)
window_handles.slice(1..).each { |win| close_window(win) }
timer = Capybara::Helpers.timer(expire_in: 10)
begin
clear_storage unless uniform_storage_clear?
@browser.navigate.to('about:blank')
wait_for_empty_page(timer)
rescue *unhandled_alert_errors
accept_unhandled_reset_alert
retry
end
execute_cdp('Storage.clearDataForOrigin', origin: '*', storageTypes: storage_types_to_clear)
end
def download_path=(path)
if @browser.respond_to?(:download_path=)
@browser.download_path = path
else
# Not yet implemented in seleniun-webdriver for edge so do it ourselves
execute_cdp('Page.setDownloadBehavior', behavior: 'allow', downloadPath: path)
end
end
private
def storage_types_to_clear
types = ['cookies']
types << 'local_storage' if clear_all_storage?
types.join(',')
end
def clear_all_storage?
storage_clears.none? false
end
def uniform_storage_clear?
storage_clears.uniq { |s| s == false }.length <= 1
end
def storage_clears
options.values_at(:clear_session_storage, :clear_local_storage)
end
def clear_storage
# Edgedriver crashes if attempt to clear storage on about:blank
url = current_url
super unless url.nil? || url.start_with?('about:')
end
def delete_all_cookies
return super if edgedriver_version < 75
execute_cdp('Network.clearBrowserCookies')
rescue *cdp_unsupported_errors
# If the CDP clear isn't supported do original limited clear
super
end
def cdp_unsupported_errors
@cdp_unsupported_errors ||= [Selenium::WebDriver::Error::WebDriverError]
end
def execute_cdp(cmd, params = {})
if browser.respond_to? :execute_cdp
browser.execute_cdp(cmd, **params)
else
args = { cmd: cmd, params: params }
result = bridge.http.call(:post, "session/#{bridge.session_id}/ms/cdp/execute", args)
result['value']
end
end
def build_node(native_node, initial_cache = {})
::Capybara::Selenium::EdgeNode.new(self, native_node, initial_cache)
end
def edgedriver_version
@edgedriver_version ||= begin
caps = browser.capabilities
caps['msedge']&.fetch('msedgedriverVersion', nil).to_f
end
end
end
Capybara::Selenium::Driver.register_specialization :edge, Capybara::Selenium::Driver::EdgeDriver
Capybara::Selenium::Driver.register_specialization :edge_chrome, Capybara::Selenium::Driver::EdgeDriver
| ruby | MIT | b3325b198464b806f07ec2011ceb532d6d5cf4ab | 2026-01-04T15:38:10.098638Z | false |
teamcapybara/capybara | https://github.com/teamcapybara/capybara/blob/b3325b198464b806f07ec2011ceb532d6d5cf4ab/lib/capybara/selenium/patches/atoms.rb | lib/capybara/selenium/patches/atoms.rb | # frozen_string_literal: true
module CapybaraAtoms
private
def read_atom(function)
@atoms ||= Hash.new do |hash, key|
hash[key] = begin
File.read(File.expand_path("../../atoms/#{key}.min.js", __FILE__))
rescue Errno::ENOENT
super
end
end
@atoms[function]
end
end
Selenium::WebDriver::Remote::Bridge.prepend CapybaraAtoms unless ENV['DISABLE_CAPYBARA_SELENIUM_OPTIMIZATIONS']
| ruby | MIT | b3325b198464b806f07ec2011ceb532d6d5cf4ab | 2026-01-04T15:38:10.098638Z | false |
teamcapybara/capybara | https://github.com/teamcapybara/capybara/blob/b3325b198464b806f07ec2011ceb532d6d5cf4ab/lib/capybara/selenium/patches/is_displayed.rb | lib/capybara/selenium/patches/is_displayed.rb | # frozen_string_literal: true
module Capybara
module Selenium
module IsDisplayed
def commands(command)
case command
when :is_element_displayed
[:get, 'session/:session_id/element/:id/displayed']
else
super
end
end
end
end
end
| ruby | MIT | b3325b198464b806f07ec2011ceb532d6d5cf4ab | 2026-01-04T15:38:10.098638Z | false |
teamcapybara/capybara | https://github.com/teamcapybara/capybara/blob/b3325b198464b806f07ec2011ceb532d6d5cf4ab/lib/capybara/selenium/patches/logs.rb | lib/capybara/selenium/patches/logs.rb | # frozen_string_literal: true
module Capybara
module Selenium
module ChromeLogs
LOG_MSG = <<~MSG
Chromedriver 75+ defaults to W3C mode. Please upgrade to chromedriver >= \
75.0.3770.90 if you need to access logs while in W3C compliant mode.
MSG
COMMANDS = {
get_available_log_types: [:get, 'session/:session_id/se/log/types'],
get_log: [:post, 'session/:session_id/se/log'],
get_log_legacy: [:post, 'session/:session_id/log']
}.freeze
def commands(command)
COMMANDS[command] || super
end
def available_log_types
types = execute :get_available_log_types
Array(types).map(&:to_sym)
rescue ::Selenium::WebDriver::Error::UnknownCommandError
raise NotImplementedError, LOG_MSG
end
def log(type)
data = begin
execute :get_log, {}, type: type.to_s
rescue ::Selenium::WebDriver::Error::UnknownCommandError
execute :get_log_legacy, {}, type: type.to_s
end
Array(data).map do |l|
::Selenium::WebDriver::LogEntry.new l.fetch('level', 'UNKNOWN'), l.fetch('timestamp'), l.fetch('message')
rescue KeyError
next
end
rescue ::Selenium::WebDriver::Error::UnknownCommandError
raise NotImplementedError, LOG_MSG
end
end
end
end
| ruby | MIT | b3325b198464b806f07ec2011ceb532d6d5cf4ab | 2026-01-04T15:38:10.098638Z | false |
teamcapybara/capybara | https://github.com/teamcapybara/capybara/blob/b3325b198464b806f07ec2011ceb532d6d5cf4ab/lib/capybara/selenium/patches/pause_duration_fix.rb | lib/capybara/selenium/patches/pause_duration_fix.rb | # frozen_string_literal: true
module PauseDurationFix
def encode
super.tap { |output| output[:duration] ||= 0 }
end
end
Selenium::WebDriver::Interactions::Pause.prepend PauseDurationFix
| ruby | MIT | b3325b198464b806f07ec2011ceb532d6d5cf4ab | 2026-01-04T15:38:10.098638Z | false |
teamcapybara/capybara | https://github.com/teamcapybara/capybara/blob/b3325b198464b806f07ec2011ceb532d6d5cf4ab/lib/capybara/selenium/patches/persistent_client.rb | lib/capybara/selenium/patches/persistent_client.rb | # frozen_string_literal: true
module Capybara
module Selenium
class PersistentClient < ::Selenium::WebDriver::Remote::Http::Default
def close
super
@http.finish if @http&.started?
end
private
def http
super.tap do |http|
http.start unless http.started?
end
end
end
end
end
| ruby | MIT | b3325b198464b806f07ec2011ceb532d6d5cf4ab | 2026-01-04T15:38:10.098638Z | false |
teamcapybara/capybara | https://github.com/teamcapybara/capybara/blob/b3325b198464b806f07ec2011ceb532d6d5cf4ab/lib/capybara/node/actions.rb | lib/capybara/node/actions.rb | # frozen_string_literal: true
module Capybara
module Node
module Actions
# @!macro waiting_behavior
# If the driver is capable of executing JavaScript, this method will wait for a set amount of time
# and continuously retry finding the element until either the element is found or the time
# expires. The length of time this method will wait is controlled through {Capybara.configure default_max_wait_time}.
#
# @option options [false, true, Numeric] wait
# Maximum time to wait for matching element to appear. Defaults to {Capybara.configure default_max_wait_time}.
##
#
# Finds a button or link and clicks it. See {#click_button} and
# {#click_link} for what locator will match against for each type of element.
#
# @overload click_link_or_button([locator], **options)
# @macro waiting_behavior
# @param [String] locator See {#click_button} and {#click_link}
#
# @return [Capybara::Node::Element] The element clicked
#
def click_link_or_button(locator = nil, **options)
find(:link_or_button, locator, **options).click
end
alias_method :click_on, :click_link_or_button
##
#
# Finds a link by id, {Capybara.configure test_id} attribute, text or title and clicks it. Also looks at image
# alt text inside the link.
#
# @overload click_link([locator], **options)
# @macro waiting_behavior
# @param [String] locator text, id, {Capybara.configure test_id} attribute, title or nested image's alt attribute
# @param [Hash] options See {Capybara::Node::Finders#find_link}
#
# @return [Capybara::Node::Element] The element clicked
def click_link(locator = nil, **options)
find(:link, locator, **options).click
end
##
#
# Finds a button on the page and clicks it.
# This can be any `<input>` element of type submit, reset, image, button or it can be a
# `<button>` element. All buttons can be found by their id, name, {Capybara.configure test_id} attribute, value, or title. `<button>` elements can also be found
# by their text content, and image `<input>` elements by their alt attribute.
#
# @overload click_button([locator], **options)
# @macro waiting_behavior
# @param [String] locator Which button to find
# @param [Hash] options See {Capybara::Node::Finders#find_button}
# @return [Capybara::Node::Element] The element clicked
def click_button(locator = nil, **options)
find(:button, locator, **options).click
end
##
#
# Locate a text field or text area and fill it in with the given text.
# The field can be found via its name, id, {Capybara.configure test_id} attribute, placeholder, or label text.
# If no locator is provided this will operate on self or a descendant.
#
# # will fill in a descendant fillable field with name, id, or label text matching 'Name'
# page.fill_in 'Name', with: 'Bob'
#
# # will fill in `el` if it's a fillable field
# el.fill_in with: 'Tom'
#
#
# @overload fill_in([locator], with:, **options)
# @param [String] locator Which field to fill in
# @param [Hash] options
# @param with: [String] The value to fill in
# @macro waiting_behavior
# @option options [String] currently_with The current value property of the field to fill in
# @option options [Boolean] multiple Match fields that can have multiple values?
# @option options [String, Regexp] id Match fields that match the id attribute
# @option options [String] name Match fields that match the name attribute
# @option options [String] placeholder Match fields that match the placeholder attribute
# @option options [String, Array<String>, Regexp] class Match fields that match the class(es) provided
# @option options [Hash] fill_options Driver specific options regarding how to fill fields (Defaults come from {Capybara.configure default_set_options})
#
# @return [Capybara::Node::Element] The element filled in
def fill_in(locator = nil, with:, currently_with: nil, fill_options: {}, **find_options)
find_options[:with] = currently_with if currently_with
find_options[:allow_self] = true if locator.nil?
find(:fillable_field, locator, **find_options).set(with, **fill_options)
end
# @!macro label_click
# @option options [Boolean, Hash] allow_label_click
# Attempt to click the label to toggle state if element is non-visible. Defaults to {Capybara.configure automatic_label_click}.
# If set to a Hash it is passed as options to the `click` on the label
##
#
# Find a descendant radio button and mark it as checked. The radio button can be found
# via name, id, {Capybara.configure test_id} attribute or label text. If no locator is
# provided this will match against self or a descendant.
#
# # will choose a descendant radio button with a name, id, or label text matching 'Male'
# page.choose('Male')
#
# # will choose `el` if it's a radio button element
# el.choose()
#
# @overload choose([locator], **options)
# @param [String] locator Which radio button to choose
#
# @option options [String] option Value of the radio_button to choose
# @option options [String, Regexp] id Match fields that match the id attribute
# @option options [String] name Match fields that match the name attribute
# @option options [String, Array<String>, Regexp] class Match fields that match the class(es) provided
# @macro waiting_behavior
# @macro label_click
#
# @return [Capybara::Node::Element] The element chosen or the label clicked
def choose(locator = nil, **options)
_check_with_label(:radio_button, true, locator, **options)
end
##
#
# Find a descendant check box and mark it as checked. The check box can be found
# via name, id, {Capybara.configure test_id} attribute, or label text. If no locator
# is provided this will match against self or a descendant.
#
# # will check a descendant checkbox with a name, id, or label text matching 'German'
# page.check('German')
#
# # will check `el` if it's a checkbox element
# el.check()
#
#
# @overload check([locator], **options)
# @param [String] locator Which check box to check
#
# @option options [String] option Value of the checkbox to select
# @option options [String, Regexp] id Match fields that match the id attribute
# @option options [String] name Match fields that match the name attribute
# @option options [String, Array<String>, Regexp] class Match fields that match the class(es) provided
# @macro label_click
# @macro waiting_behavior
#
# @return [Capybara::Node::Element] The element checked or the label clicked
def check(locator = nil, **options)
_check_with_label(:checkbox, true, locator, **options)
end
##
#
# Find a descendant check box and uncheck it. The check box can be found
# via name, id, {Capybara.configure test_id} attribute, or label text. If
# no locator is provided this will match against self or a descendant.
#
# # will uncheck a descendant checkbox with a name, id, or label text matching 'German'
# page.uncheck('German')
#
# # will uncheck `el` if it's a checkbox element
# el.uncheck()
#
#
# @overload uncheck([locator], **options)
# @param [String] locator Which check box to uncheck
#
# @option options [String] option Value of the checkbox to deselect
# @option options [String, Regexp] id Match fields that match the id attribute
# @option options [String] name Match fields that match the name attribute
# @option options [String, Array<String>, Regexp] class Match fields that match the class(es) provided
# @macro label_click
# @macro waiting_behavior
#
# @return [Capybara::Node::Element] The element unchecked or the label clicked
def uncheck(locator = nil, **options)
_check_with_label(:checkbox, false, locator, **options)
end
##
#
# If `from` option is present, {#select} finds a select box, or text input with associated datalist,
# on the page and selects a particular option from it.
# Otherwise it finds an option inside current scope and selects it.
# If the select box is a multiple select, {#select} can be called multiple times to select more than
# one option.
# The select box can be found via its name, id, {Capybara.configure test_id} attribute, or label text.
# The option can be found by its text.
#
# page.select 'March', from: 'Month'
#
# @overload select(value = nil, from: nil, **options)
# @macro waiting_behavior
#
# @param value [String] Which option to select
# @param from [String] The id, {Capybara.configure test_id} attribute, name or label of the select box
#
# @return [Capybara::Node::Element] The option element selected
def select(value = nil, from: nil, **options)
raise ArgumentError, 'The :from option does not take an element' if from.is_a? Capybara::Node::Element
el = from ? find_select_or_datalist_input(from, options) : self
if el.respond_to?(:tag_name) && (el.tag_name == 'input')
select_datalist_option(el, value)
else
el.find(:option, value, **options).select_option
end
end
##
#
# Find a select box on the page and unselect a particular option from it. If the select
# box is a multiple select, {#unselect} can be called multiple times to unselect more than
# one option. The select box can be found via its name, id, {Capybara.configure test_id} attribute,
# or label text.
#
# page.unselect 'March', from: 'Month'
#
# @overload unselect(value = nil, from: nil, **options)
# @macro waiting_behavior
#
# @param value [String] Which option to unselect
# @param from [String] The id, {Capybara.configure test_id} attribute, name or label of the select box
#
#
# @return [Capybara::Node::Element] The option element unselected
def unselect(value = nil, from: nil, **options)
raise ArgumentError, 'The :from option does not take an element' if from.is_a? Capybara::Node::Element
scope = from ? find(:select, from, **options) : self
scope.find(:option, value, **options).unselect_option
end
##
#
# Find a descendant file field on the page and attach a file given its path. There are two ways to use
# {#attach_file}, in the first method the file field can be found via its name, id,
# {Capybara.configure test_id} attribute, or label text. In the case of the file field being hidden for
# styling reasons the `make_visible` option can be used to temporarily change the CSS of
# the file field, attach the file, and then revert the CSS back to original. If no locator is
# passed this will match self or a descendant.
# The second method, which is currently in beta and may be changed/removed, involves passing a block
# which performs whatever actions would trigger the file chooser to appear.
#
# # will attach file to a descendant file input element that has a name, id, or label_text matching 'My File'
# page.attach_file('My File', '/path/to/file.png')
#
# # will attach file to el if it's a file input element
# el.attach_file('/path/to/file.png')
#
# # will attach file to whatever file input is triggered by the block
# page.attach_file('/path/to/file.png') do
# page.find('#upload_button').click
# end
#
# @overload attach_file([locator], paths, **options)
# @macro waiting_behavior
#
# @param [String] locator Which field to attach the file to
# @param [String, Array<String>] paths The path(s) of the file(s) that will be attached
#
# @option options [Symbol] match
# The matching strategy to use (:one, :first, :prefer_exact, :smart). Defaults to {Capybara.configure match}.
# @option options [Boolean] exact
# Match the exact label name/contents or accept a partial match. Defaults to {Capybara.configure exact}.
# @option options [Boolean] multiple Match field which allows multiple file selection
# @option options [String, Regexp] id Match fields that match the id attribute
# @option options [String] name Match fields that match the name attribute
# @option options [String, Array<String>, Regexp] class Match fields that match the class(es) provided
# @option options [true, Hash] make_visible
# A Hash of CSS styles to change before attempting to attach the file, if `true`, `{ opacity: 1, display: 'block', visibility: 'visible' }` is used (may not be supported by all drivers).
# @overload attach_file(paths, &blk)
# @param [String, Array<String>] paths The path(s) of the file(s) that will be attached
# @yield Block whose actions will trigger the system file chooser to be shown
# @return [Capybara::Node::Element] The file field element
def attach_file(locator = nil, paths, make_visible: nil, **options) # rubocop:disable Style/OptionalArguments
if locator && block_given?
raise ArgumentError, '`#attach_file` does not support passing both a locator and a block'
end
Array(paths).each do |path|
raise Capybara::FileNotFound, "cannot attach file, #{path} does not exist" unless File.exist?(path.to_s)
end
options[:allow_self] = true if locator.nil?
if block_given?
begin
execute_script CAPTURE_FILE_ELEMENT_SCRIPT
yield
file_field = evaluate_script 'window._capybara_clicked_file_input'
raise ArgumentError, "Capybara was unable to determine the file input you're attaching to" unless file_field
rescue ::Capybara::NotSupportedByDriverError
warn 'Block mode of `#attach_file` is not supported by the current driver - ignoring.'
end
end
# Allow user to update the CSS style of the file input since they are so often hidden on a page
if make_visible
ff = file_field || find(:file_field, locator, **options.merge(visible: :all))
while_visible(ff, make_visible) { |el| el.set(paths) }
else
(file_field || find(:file_field, locator, **options)).set(paths)
end
end
private
def find_select_or_datalist_input(from, options)
synchronize(Capybara::Queries::BaseQuery.wait(options, session_options.default_max_wait_time)) do
find(:select, from, **options)
rescue Capybara::ElementNotFound => select_error # rubocop:disable Naming/RescuedExceptionsVariableName
raise if %i[selected with_selected multiple].any? { |option| options.key?(option) }
begin
find(:datalist_input, from, **options)
rescue Capybara::ElementNotFound => dlinput_error
raise Capybara::ElementNotFound, "#{select_error.message} and #{dlinput_error.message}"
end
end
end
def select_datalist_option(input, value)
datalist_options = input.evaluate_script(DATALIST_OPTIONS_SCRIPT)
option = datalist_options.find { |opt| opt.values_at('value', 'label').include?(value) }
raise ::Capybara::ElementNotFound, %(Unable to find datalist option "#{value}") unless option
input.set(option['value'])
rescue ::Capybara::NotSupportedByDriverError
# Implement for drivers that don't support JS
datalist = find(:xpath, XPath.descendant(:datalist)[XPath.attr(:id) == input[:list]], visible: false)
option = datalist.find(:datalist_option, value, disabled: false)
input.set(option.value)
end
def while_visible(element, visible_css)
if visible_css == true
visible_css = { opacity: 1, display: 'block', visibility: 'visible', width: 'auto', height: 'auto' }
end
_update_style(element, visible_css)
unless element.visible?
raise ExpectationNotMet, 'The style changes in :make_visible did not make the file input visible'
end
begin
yield element
ensure
_reset_style(element)
end
end
def _update_style(element, style)
element.execute_script(UPDATE_STYLE_SCRIPT, style)
rescue Capybara::NotSupportedByDriverError
warn 'The :make_visible option is not supported by the current driver - ignoring'
end
def _reset_style(element)
element.execute_script(RESET_STYLE_SCRIPT)
rescue StandardError # rubocop:disable Lint/SuppressedException -- swallow extra errors
end
def _check_with_label(selector, checked, locator,
allow_label_click: session_options.automatic_label_click, **options)
options[:allow_self] = true if locator.nil?
synchronize(Capybara::Queries::BaseQuery.wait(options, session_options.default_max_wait_time)) do
el = find(selector, locator, **options)
el.set(checked)
rescue StandardError => e
raise unless allow_label_click && catch_error?(e)
begin
el ||= find(selector, locator, **options.merge(visible: :all))
unless el.checked? == checked
el.session
.find(:label, for: el, visible: true, match: :first)
.click(**(Hash.try_convert(allow_label_click) || {}))
end
rescue StandardError # swallow extra errors - raise original
raise e
end
end
end
UPDATE_STYLE_SCRIPT = <<~JS
this.capybara_style_cache = this.style.cssText;
var css = arguments[0];
for (var prop in css){
if (css.hasOwnProperty(prop)) {
this.style.setProperty(prop, css[prop], "important");
}
}
JS
RESET_STYLE_SCRIPT = <<~JS
if (this.hasOwnProperty('capybara_style_cache')) {
this.style.cssText = this.capybara_style_cache;
delete this.capybara_style_cache;
}
JS
DATALIST_OPTIONS_SCRIPT = <<~JS
Array.prototype.slice.call((this.list||{}).options || []).
filter(function(el){ return !el.disabled }).
map(function(el){ return { "value": el.value, "label": el.label} })
JS
CAPTURE_FILE_ELEMENT_SCRIPT = <<~JS
document.addEventListener('click', function file_catcher(e){
if (e.target.matches("input[type='file']")) {
window._capybara_clicked_file_input = e.target;
this.removeEventListener('click', file_catcher);
e.preventDefault();
}
}, {capture: true})
JS
end
end
end
| ruby | MIT | b3325b198464b806f07ec2011ceb532d6d5cf4ab | 2026-01-04T15:38:10.098638Z | false |
teamcapybara/capybara | https://github.com/teamcapybara/capybara/blob/b3325b198464b806f07ec2011ceb532d6d5cf4ab/lib/capybara/node/element.rb | lib/capybara/node/element.rb | # frozen_string_literal: true
module Capybara
module Node
##
#
# A {Capybara::Node::Element} represents a single element on the page. It is possible
# to interact with the contents of this element the same as with a document:
#
# session = Capybara::Session.new(:rack_test, my_app)
#
# bar = session.find('#bar') # from Capybara::Node::Finders
# bar.select('Baz', from: 'Quox') # from Capybara::Node::Actions
#
# {Capybara::Node::Element} also has access to HTML attributes and other properties of the
# element:
#
# bar.value
# bar.text
# bar[:title]
#
# @see Capybara::Node
#
class Element < Base
def initialize(session, base, query_scope, query)
super(session, base)
@query_scope = query_scope
@query = query
@allow_reload = false
@query_idx = nil
end
def allow_reload!(idx = nil)
@query_idx = idx
@allow_reload = true
end
##
#
# @return [Object] The native element from the driver, this allows access to driver specific methods
#
def native
synchronize { base.native }
end
##
#
# Retrieve the text of the element. If {Capybara.configure ignore_hidden_elements}
# is `true`, which it is by default, then this will return only text
# which is visible. The exact semantics of this may differ between
# drivers, but generally any text within elements with `display:none` is
# ignored. This behaviour can be overridden by passing `:all` to this
# method.
#
# @param type [:all, :visible] Whether to return only visible or all text
# @return [String] The text of the element
#
def text(type = nil, normalize_ws: false)
type ||= :all unless session_options.ignore_hidden_elements || session_options.visible_text_only
txt = synchronize { type == :all ? base.all_text : base.visible_text }
normalize_ws ? txt.gsub(/[[:space:]]+/, ' ').strip : txt
end
##
#
# Retrieve the given attribute.
#
# element[:title] # => HTML title attribute
#
# @param [Symbol] attribute The attribute to retrieve
# @return [String] The value of the attribute
#
def [](attribute)
synchronize { base[attribute] }
end
##
#
# Retrieve the given CSS styles.
#
# element.style('color', 'font-size') # => Computed values of CSS 'color' and 'font-size' styles
#
# @param [Array<String>] styles Names of the desired CSS properties
# @return [Hash] Hash of the CSS property names to computed values
#
def style(*styles)
styles = styles.flatten.map(&:to_s)
raise ArgumentError, 'You must specify at least one CSS style' if styles.empty?
begin
synchronize { base.style(styles) }
rescue NotImplementedError => e
begin
evaluate_script(STYLE_SCRIPT, *styles)
rescue Capybara::NotSupportedByDriverError
raise e
end
end
end
##
#
# @return [String] The value of the form element
#
def value
synchronize { base.value }
end
##
#
# Set the value of the form element to the given value.
#
# @param [String] value The new value
# @param [Hash] options Driver specific options for how to set the value. Take default values from {Capybara.configure default_set_options}.
#
# @return [Capybara::Node::Element] The element
def set(value, **options)
if ENV.fetch('CAPYBARA_THOROUGH', nil) && readonly?
raise Capybara::ReadOnlyElementError, "Attempt to set readonly element with value: #{value}"
end
options = session_options.default_set_options.to_h.merge(options)
synchronize { base.set(value, **options) }
self
end
##
#
# Select this node if it is an option element inside a select tag.
#
# @!macro action_waiting_behavior
# If the driver dynamic pages (JS) and the element is currently non-interactable, this method will
# continuously retry the action until either the element becomes interactable or the maximum
# wait time expires.
#
# @param [false, Numeric] wait
# Maximum time to wait for the action to succeed. Defaults to {Capybara.configure default_max_wait_time}.
# @return [Capybara::Node::Element] The element
def select_option(wait: nil)
synchronize(wait) { base.select_option }
self
end
##
#
# Unselect this node if it is an option element inside a multiple select tag.
#
# @macro action_waiting_behavior
# @return [Capybara::Node::Element] The element
def unselect_option(wait: nil)
synchronize(wait) { base.unselect_option }
self
end
##
#
# Click the Element.
#
# @macro action_waiting_behavior
# @!macro click_modifiers
# Both x: and y: must be specified if an offset is wanted, if not specified the click will occur at the middle of the element.
# @overload $0(*modifier_keys, wait: nil, **offset)
# @param *modifier_keys [:alt, :control, :meta, :shift] ([]) Keys to be held down when clicking
# @option options [Integer] x X coordinate to offset the click location. If {Capybara.configure w3c_click_offset} is `true` the
# offset will be from the element center, otherwise it will be from the top left corner of the element
# @option options [Integer] y Y coordinate to offset the click location. If {Capybara.configure w3c_click_offset} is `true` the
# offset will be from the element center, otherwise it will be from the top left corner of the element
# @option options [Float] delay Delay between the mouse down and mouse up events in seconds (0)
# @return [Capybara::Node::Element] The element
def click(*keys, **options)
perform_click_action(keys, **options) do |k, opts|
base.click(k, **opts)
end
end
##
#
# Right Click the Element.
#
# @macro action_waiting_behavior
# @macro click_modifiers
# @option options [Float] delay Delay between the mouse down and mouse up events in seconds (0)
# @return [Capybara::Node::Element] The element
def right_click(*keys, **options)
perform_click_action(keys, **options) do |k, opts|
base.right_click(k, **opts)
end
end
##
#
# Double Click the Element.
#
# @macro action_waiting_behavior
# @macro click_modifiers
# @return [Capybara::Node::Element] The element
def double_click(*keys, **options)
perform_click_action(keys, **options) do |k, opts|
base.double_click(k, **opts)
end
end
##
#
# Send Keystrokes to the Element.
#
# @overload send_keys(keys, ...)
# @param keys [String, Symbol, Array<String,Symbol>]
#
# Examples:
#
# element.send_keys "foo" #=> value: 'foo'
# element.send_keys "tet", :left, "s" #=> value: 'test'
# element.send_keys [:control, 'a'], :space #=> value: ' ' - assuming ctrl-a selects all contents
#
# Symbols supported for keys:
# * :cancel
# * :help
# * :backspace
# * :tab
# * :clear
# * :return
# * :enter
# * :shift
# * :control
# * :alt
# * :pause
# * :escape
# * :space
# * :page_up
# * :page_down
# * :end
# * :home
# * :left
# * :up
# * :right
# * :down
# * :insert
# * :delete
# * :semicolon
# * :equals
# * :numpad0
# * :numpad1
# * :numpad2
# * :numpad3
# * :numpad4
# * :numpad5
# * :numpad6
# * :numpad7
# * :numpad8
# * :numpad9
# * :multiply - numeric keypad *
# * :add - numeric keypad +
# * :separator - numeric keypad 'separator' key ??
# * :subtract - numeric keypad -
# * :decimal - numeric keypad .
# * :divide - numeric keypad /
# * :f1
# * :f2
# * :f3
# * :f4
# * :f5
# * :f6
# * :f7
# * :f8
# * :f9
# * :f10
# * :f11
# * :f12
# * :meta
# * :command - alias of :meta
#
# @return [Capybara::Node::Element] The element
def send_keys(*args)
synchronize { base.send_keys(*args) }
self
end
##
#
# Hover on the Element.
#
# @return [Capybara::Node::Element] The element
def hover
synchronize { base.hover }
self
end
##
#
# @return [String] The tag name of the element
#
def tag_name
# Element type is immutable so cache it
@tag_name ||= initial_cache[:tag_name] || synchronize { base.tag_name }
end
##
#
# Whether or not the element is visible. Not all drivers support CSS, so
# the result may be inaccurate.
#
# @return [Boolean] Whether the element is visible
#
def visible?
synchronize { base.visible? }
end
##
#
# Whether or not the element is currently in the viewport and it (or descendants)
# would be considered clickable at the elements center point.
#
# @return [Boolean] Whether the elements center is obscured.
#
def obscured?
synchronize { base.obscured? }
end
##
#
# Whether or not the element is checked.
#
# @return [Boolean] Whether the element is checked
#
def checked?
synchronize { base.checked? }
end
##
#
# Whether or not the element is selected.
#
# @return [Boolean] Whether the element is selected
#
def selected?
synchronize { base.selected? }
end
##
#
# Whether or not the element is disabled.
#
# @return [Boolean] Whether the element is disabled
#
def disabled?
synchronize { base.disabled? }
end
##
#
# Whether or not the element is readonly.
#
# @return [Boolean] Whether the element is readonly
#
def readonly?
synchronize { base.readonly? }
end
##
#
# Whether or not the element supports multiple results.
#
# @return [Boolean] Whether the element supports multiple results.
#
def multiple?
synchronize { base.multiple? }
end
##
#
# An XPath expression describing where on the page the element can be found.
#
# @return [String] An XPath expression
#
def path
synchronize { base.path }
end
def rect
synchronize { base.rect }
end
##
#
# Trigger any event on the current element, for example mouseover or focus
# events. Not supported with the Selenium driver, and SHOULDN'T BE USED IN TESTING unless you
# fully understand why you're using it, that it can allow actions a user could never
# perform, and that it may completely invalidate your test.
#
# @param [String] event The name of the event to trigger
#
# @return [Capybara::Node::Element] The element
def trigger(event)
synchronize { base.trigger(event) }
self
end
##
#
# Drag the element to the given other element.
#
# source = page.find('#foo')
# target = page.find('#bar')
# source.drag_to(target)
#
# @param [Capybara::Node::Element] node The element to drag to
# @param [Hash] options Driver specific options for dragging. May not be supported by all drivers.
# @option options [Numeric] :delay (0.05) When using Chrome/Firefox with Selenium and HTML5 dragging this is the number
# of seconds between each stage of the drag.
# @option options [Boolean] :html5 When using Chrome/Firefox with Selenium enables to force the use of HTML5
# (true) or legacy (false) dragging. If not specified the driver will attempt to
# detect the correct method to use.
# @option options [Array<Symbol>,Symbol] :drop_modifiers Modifier keys which should be held while the dragged element is dropped.
#
#
# @return [Capybara::Node::Element] The dragged element
def drag_to(node, **options)
synchronize { base.drag_to(node.base, **options) }
self
end
##
#
# Drop items on the current element.
#
# target = page.find('#foo')
# target.drop('/some/path/file.csv')
#
# @overload drop(path, ...)
# @param [String, #to_path] path Location of the file to drop on the element
#
# @overload drop(strings, ...)
# @param [Hash] strings A hash of type to data to be dropped - `{ "text/url" => "https://www.google.com" }`
#
# @return [Capybara::Node::Element] The element
def drop(*args)
options = args.map { |arg| arg.respond_to?(:to_path) ? arg.to_path : arg }
synchronize { base.drop(*options) }
self
end
##
#
# Scroll the page or element.
#
# @overload scroll_to(position, offset: [0,0])
# Scroll the page or element to its top, bottom or middle.
# @param [:top, :bottom, :center, :current] position
# @param [[Integer, Integer]] offset
#
# @overload scroll_to(element, align: :top)
# Scroll the page or current element until the given element is aligned at the top, bottom, or center of it.
# @param [Capybara::Node::Element] element The element to be scrolled into view
# @param [:top, :bottom, :center] align Where to align the element being scrolled into view with relation to the current page/element if possible
#
# @overload scroll_to(x,y)
# @param [Integer] x Horizontal scroll offset
# @param [Integer] y Vertical scroll offset
#
# @return [Capybara::Node::Element] The element
def scroll_to(pos_or_el_or_x, y = nil, align: :top, offset: nil)
case pos_or_el_or_x
when Symbol
synchronize { base.scroll_to(nil, pos_or_el_or_x) } unless pos_or_el_or_x == :current
when Capybara::Node::Element
synchronize { base.scroll_to(pos_or_el_or_x.base, align) }
else
synchronize { base.scroll_to(nil, nil, [pos_or_el_or_x, y]) }
end
synchronize { base.scroll_by(*offset) } unless offset.nil?
self
end
##
#
# Return the shadow_root for the current element
#
# @return [Capybara::Node::Element] The shadow root
def shadow_root
root = synchronize { base.shadow_root }
root && Capybara::Node::Element.new(session, root, nil, nil)
end
##
#
# Execute the given JS in the context of the element not returning a result. This is useful for scripts that return
# complex objects, such as jQuery statements. {#execute_script} should be used over
# {#evaluate_script} whenever a result is not expected or needed. `this` in the script will refer to the element this is called on.
#
# @param [String] script A string of JavaScript to execute
# @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 drivers
#
def execute_script(script, *args)
session.execute_script(<<~JS, self, *args)
(function (){
#{script}
}).apply(arguments[0], Array.prototype.slice.call(arguments,1));
JS
end
##
#
# Evaluate the given JS in the context of the element and return the result. Be careful when using this with
# scripts that return complex objects, such as jQuery statements. {#execute_script} might
# be a better alternative. `this` in the script will refer to the element this is called on.
#
# @param [String] script A string of JavaScript to evaluate
# @return [Object] The result of the evaluated JavaScript (may be driver specific)
#
def evaluate_script(script, *args)
session.evaluate_script(<<~JS, self, *args)
(function(){
return #{script.strip}
}).apply(arguments[0], Array.prototype.slice.call(arguments,1));
JS
end
##
#
# Evaluate the given JavaScript in the context of the element and obtain the result from a
# callback function which will be passed as the last argument to the script. `this` in the
# script will refer to the element this is called on.
#
# @param [String] script A string of JavaScript to evaluate
# @return [Object] The result of the evaluated JavaScript (may be driver specific)
#
def evaluate_async_script(script, *args)
session.evaluate_async_script(<<~JS, self, *args)
(function (){
#{script}
}).apply(arguments[0], Array.prototype.slice.call(arguments,1));
JS
end
##
#
# Toggle the elements background color between white and black for a period of time.
#
# @return [Capybara::Node::Element] The element
def flash
execute_script(<<~JS, 100)
async function flash(el, delay){
var old_bg = el.style.backgroundColor;
var colors = ["black", "white"];
for(var i=0; i<20; i++){
el.style.backgroundColor = colors[i % colors.length];
await new Promise(resolve => setTimeout(resolve, delay));
}
el.style.backgroundColor = old_bg;
}
flash(this, arguments[0]);
JS
self
end
# @api private
def reload
return self unless @allow_reload
begin
reloaded = @query.resolve_for(query_scope ? query_scope.reload : session)[@query_idx.to_i]
@base = reloaded.base if reloaded
rescue StandardError => e
raise e unless catch_error?(e)
end
self
end
##
#
# A human-readable representation of the element.
#
# @return [String] A string representation
def inspect
%(#<Capybara::Node::Element tag="#{base.tag_name}" path="#{base.path}">)
rescue NotSupportedByDriverError
%(#<Capybara::Node::Element tag="#{base.tag_name}">)
rescue *session.driver.invalid_element_errors
%(Obsolete #<Capybara::Node::Element>)
end
# @api private
def initial_cache
base.respond_to?(:initial_cache) ? base.initial_cache : {}
end
STYLE_SCRIPT = <<~JS
(function(){
var s = window.getComputedStyle(this);
var result = {};
for (var i = arguments.length; i--; ) {
var property_name = arguments[i];
result[property_name] = s.getPropertyValue(property_name);
}
return result;
}).apply(this, arguments)
JS
private
def perform_click_action(keys, wait: nil, **options)
raise ArgumentError, 'You must specify both x: and y: for a click offset' if nil ^ options[:x] ^ options[:y]
options[:offset] ||= :center if session_options.w3c_click_offset
synchronize(wait) { yield keys, options }
self
end
end
end
end
| ruby | MIT | b3325b198464b806f07ec2011ceb532d6d5cf4ab | 2026-01-04T15:38:10.098638Z | false |
teamcapybara/capybara | https://github.com/teamcapybara/capybara/blob/b3325b198464b806f07ec2011ceb532d6d5cf4ab/lib/capybara/node/matchers.rb | lib/capybara/node/matchers.rb | # frozen_string_literal: true
module Capybara
module Node
module Matchers
##
#
# Checks if a given selector is on the page or a descendant of the current node.
#
# page.has_selector?('p#foo')
# page.has_selector?(:xpath, './/p[@id="foo"]')
# page.has_selector?(:foo)
#
# By default it will check if the expression occurs at least once,
# but a different number can be specified.
#
# page.has_selector?('p.foo', count: 4)
#
# This will check if the expression occurs exactly 4 times.
#
# It also accepts all options that {Capybara::Node::Finders#all} accepts,
# such as `:text` and `:visible`.
#
# page.has_selector?('li', text: 'Horse', visible: true)
#
# {#has_selector?} can also accept XPath expressions generated by the
# XPath gem:
#
# page.has_selector?(:xpath, XPath.descendant(:p))
#
# @param (see Capybara::Node::Finders#all)
# @option options [Integer] :count (nil) Number of matching elements that should exist
# @option options [Integer] :minimum (nil) Minimum number of matching elements that should exist
# @option options [Integer] :maximum (nil) Maximum number of matching elements that should exist
# @option options [Range] :between (nil) Range of number of matching elements that should exist
# @return [Boolean] If the expression exists
#
def has_selector?(*args, **options, &optional_filter_block)
make_predicate(options) { assert_selector(*args, options, &optional_filter_block) }
end
##
#
# Checks if a given selector is not on the page or a descendant of the current node.
# Usage is identical to {#has_selector?}.
#
# @param (see #has_selector?)
# @return [Boolean]
#
def has_no_selector?(*args, **options, &optional_filter_block)
make_predicate(options) { assert_no_selector(*args, options, &optional_filter_block) }
end
##
#
# Checks if a an element has the specified CSS styles.
#
# element.matches_style?( 'color' => 'rgb(0,0,255)', 'font-size' => /px/ )
#
# @param styles [Hash]
# @return [Boolean] If the styles match
#
def matches_style?(styles = nil, **options)
styles, options = options, {} if styles.nil?
make_predicate(options) { assert_matches_style(styles, **options) }
end
##
# @deprecated Use {#matches_style?} instead.
#
def has_style?(styles = nil, **options)
Capybara::Helpers.warn "DEPRECATED: has_style? is deprecated, please use matches_style? : #{Capybara::Helpers.filter_backtrace(caller)}"
matches_style?(styles, **options)
end
##
#
# Asserts that a given selector is on the page or a descendant of the current node.
#
# page.assert_selector('p#foo')
# page.assert_selector(:xpath, './/p[@id="foo"]')
# page.assert_selector(:foo)
#
# By default it will check if the expression occurs at least once,
# but a different number can be specified.
#
# page.assert_selector('p#foo', count: 4)
#
# This will check if the expression occurs exactly 4 times. See
# {Capybara::Node::Finders#all} for other available result size options.
#
# If a `:count` of 0 is specified, it will behave like {#assert_no_selector};
# however, use of that method is preferred over this one.
#
# It also accepts all options that {Capybara::Node::Finders#all} accepts,
# such as `:text` and `:visible`.
#
# page.assert_selector('li', text: 'Horse', visible: true)
#
# {#assert_selector} can also accept XPath expressions generated by the
# XPath gem:
#
# page.assert_selector(:xpath, XPath.descendant(:p))
#
# @param (see Capybara::Node::Finders#all)
# @option options [Integer] :count (nil) Number of times the expression should occur
# @raise [Capybara::ExpectationNotMet] If the selector does not exist
#
def assert_selector(*args, &optional_filter_block)
_verify_selector_result(args, optional_filter_block) do |result, query|
unless result.matches_count? && (result.any? || query.expects_none?)
raise Capybara::ExpectationNotMet, result.failure_message
end
end
end
##
#
# Asserts that an element has the specified CSS styles.
#
# element.assert_matches_style( 'color' => 'rgb(0,0,255)', 'font-size' => /px/ )
#
# @param styles [Hash]
# @raise [Capybara::ExpectationNotMet] If the element doesn't have the specified styles
#
def assert_matches_style(styles = nil, **options)
styles, options = options, {} if styles.nil?
query_args, query_opts = _set_query_session_options(styles, options)
query = Capybara::Queries::StyleQuery.new(*query_args, **query_opts)
synchronize(query.wait) do
raise Capybara::ExpectationNotMet, query.failure_message unless query.resolves_for?(self)
end
true
end
##
# @deprecated Use {#assert_matches_style} instead.
#
def assert_style(styles = nil, **options)
warn 'assert_style is deprecated, please use assert_matches_style instead'
assert_matches_style(styles, **options)
end
# Asserts that all of the provided selectors are present on the given page
# or descendants of the current node. If options are provided, the assertion
# will check that each locator is present with those options as well (other than `:wait`).
#
# page.assert_all_of_selectors(:custom, 'Tom', 'Joe', visible: all)
# page.assert_all_of_selectors(:css, '#my_div', 'a.not_clicked')
#
# It accepts all options that {Capybara::Node::Finders#all} accepts,
# such as `:text` and `:visible`.
#
# The `:wait` option applies to all of the selectors as a group, so all of the locators must be present
# within `:wait` (defaults to {Capybara.configure default_max_wait_time}) seconds.
#
# @overload assert_all_of_selectors([kind = Capybara.default_selector], *locators, **options)
#
def assert_all_of_selectors(*args, **options, &optional_filter_block)
_verify_multiple(*args, **options) do |selector, locator, opts|
assert_selector(selector, locator, opts, &optional_filter_block)
end
end
# Asserts that none of the provided selectors are present on the given page
# or descendants of the current node. If options are provided, the assertion
# will check that each locator is not present with those options as well (other than `:wait`).
#
# page.assert_none_of_selectors(:custom, 'Tom', 'Joe', visible: all)
# page.assert_none_of_selectors(:css, '#my_div', 'a.not_clicked')
#
# It accepts all options that {Capybara::Node::Finders#all} accepts,
# such as `:text` and `:visible`.
#
# The `:wait` option applies to all of the selectors as a group, so none of the locators must be present
# within `:wait` (defaults to {Capybara.configure default_max_wait_time}) seconds.
#
# @overload assert_none_of_selectors([kind = Capybara.default_selector], *locators, **options)
#
def assert_none_of_selectors(*args, **options, &optional_filter_block)
_verify_multiple(*args, **options) do |selector, locator, opts|
assert_no_selector(selector, locator, opts, &optional_filter_block)
end
end
# Asserts that any of the provided selectors are present on the given page
# or descendants of the current node. If options are provided, the assertion
# will check that each locator is present with those options as well (other than `:wait`).
#
# page.assert_any_of_selectors(:custom, 'Tom', 'Joe', visible: all)
# page.assert_any_of_selectors(:css, '#my_div', 'a.not_clicked')
#
# It accepts all options that {Capybara::Node::Finders#all} accepts,
# such as `:text` and `:visible`.
#
# The `:wait` option applies to all of the selectors as a group, so any of the locators must be present
# within `:wait` (defaults to {Capybara.configure default_max_wait_time}) seconds.
#
# @overload assert_any_of_selectors([kind = Capybara.default_selector], *locators, **options)
#
def assert_any_of_selectors(*args, wait: nil, **options, &optional_filter_block)
wait = session_options.default_max_wait_time if wait.nil?
selector = extract_selector(args)
synchronize(wait) do
res = args.map do |locator|
assert_selector(selector, locator, options, &optional_filter_block)
break nil
rescue Capybara::ExpectationNotMet => e
e.message
end
raise Capybara::ExpectationNotMet, res.join(' or ') if res
true
end
end
##
#
# Asserts that a given selector is not on the page or a descendant of the current node.
# Usage is identical to {#assert_selector}.
#
# Query options such as `:count`, `:minimum`, `:maximum`, and `:between` are
# considered to be an integral part of the selector. This will return
# `true`, for example, if a page contains 4 anchors but the query expects 5:
#
# page.assert_no_selector('a', minimum: 1) # Found, raises Capybara::ExpectationNotMet
# page.assert_no_selector('a', count: 4) # Found, raises Capybara::ExpectationNotMet
# page.assert_no_selector('a', count: 5) # Not Found, returns true
#
# @param (see #assert_selector)
# @raise [Capybara::ExpectationNotMet] If the selector exists
#
def assert_no_selector(*args, &optional_filter_block)
_verify_selector_result(args, optional_filter_block) do |result, query|
if result.matches_count? && (!result.empty? || query.expects_none?)
raise Capybara::ExpectationNotMet, result.negative_failure_message
end
end
end
##
#
# Checks if a given XPath expression is on the page or a descendant of the current node.
#
# page.has_xpath?('.//p[@id="foo"]')
#
# By default it will check if the expression occurs at least once,
# but a different number can be specified.
#
# page.has_xpath?('.//p[@id="foo"]', count: 4)
#
# This will check if the expression occurs exactly 4 times.
#
# It also accepts all options that {Capybara::Node::Finders#all} accepts,
# such as `:text` and `:visible`.
#
# page.has_xpath?('.//li', text: 'Horse', visible: true)
#
# {#has_xpath?} can also accept XPath expressions generated by the
# XPath gem:
#
# xpath = XPath.generate { |x| x.descendant(:p) }
# page.has_xpath?(xpath)
#
# @param [String] path An XPath expression
# @param options (see Capybara::Node::Finders#all)
# @option options [Integer] :count (nil) Number of times the expression should occur
# @return [Boolean] If the expression exists
#
def has_xpath?(path, **options, &optional_filter_block)
has_selector?(:xpath, path, **options, &optional_filter_block)
end
##
#
# Checks if a given XPath expression is not on the page or a descendant of the current node.
# Usage is identical to {#has_xpath?}.
#
# @param (see #has_xpath?)
# @return [Boolean]
#
def has_no_xpath?(path, **options, &optional_filter_block)
has_no_selector?(:xpath, path, **options, &optional_filter_block)
end
##
#
# Checks if a given CSS selector is on the page or a descendant of the current node.
#
# page.has_css?('p#foo')
#
# By default it will check if the selector occurs at least once,
# but a different number can be specified.
#
# page.has_css?('p#foo', count: 4)
#
# This will check if the selector occurs exactly 4 times.
#
# It also accepts all options that {Capybara::Node::Finders#all} accepts,
# such as `:text` and `:visible`.
#
# page.has_css?('li', text: 'Horse', visible: true)
#
# @param [String] path A CSS selector
# @param options (see Capybara::Node::Finders#all)
# @option options [Integer] :count (nil) Number of times the selector should occur
# @return [Boolean] If the selector exists
#
def has_css?(path, **options, &optional_filter_block)
has_selector?(:css, path, **options, &optional_filter_block)
end
##
#
# Checks if a given CSS selector is not on the page or a descendant of the current node.
# Usage is identical to {#has_css?}.
#
# @param (see #has_css?)
# @return [Boolean]
#
def has_no_css?(path, **options, &optional_filter_block)
has_no_selector?(:css, path, **options, &optional_filter_block)
end
##
#
# Checks if the page or current node has a element with the given
# local name.
#
# @param [String] locator The local name of a element to check for
# @option options [String, Regexp] The attributes values of matching elements
# @return [Boolean] Whether it exists
#
def has_element?(locator = nil, **options, &optional_filter_block)
has_selector?(:element, locator, **options, &optional_filter_block)
end
##
#
# Checks if the page or current node has no element with the given
# local name.
#
# @param (see #has_element?)
# @return [Boolean] Whether it doesn't exist
#
def has_no_element?(locator = nil, **options, &optional_filter_block)
has_no_selector?(:element, locator, **options, &optional_filter_block)
end
##
#
# Checks if the page or current node has a link with the given
# text or id.
#
# @param [String] locator The text or id of a link to check for
# @option options [String, Regexp] :href The value the href attribute must be
# @return [Boolean] Whether it exists
#
def has_link?(locator = nil, **options, &optional_filter_block)
has_selector?(:link, locator, **options, &optional_filter_block)
end
##
#
# Checks if the page or current node has no link with the given
# text or id.
#
# @param (see #has_link?)
# @return [Boolean] Whether it doesn't exist
#
def has_no_link?(locator = nil, **options, &optional_filter_block)
has_no_selector?(:link, locator, **options, &optional_filter_block)
end
##
#
# Checks if the page or current node has a button with the given
# text, value or id.
#
# @param [String] locator The text, value or id of a button to check for
# @return [Boolean] Whether it exists
#
def has_button?(locator = nil, **options, &optional_filter_block)
has_selector?(:button, locator, **options, &optional_filter_block)
end
##
#
# Checks if the page or current node has no button with the given
# text, value or id.
#
# @param [String] locator The text, value or id of a button to check for
# @return [Boolean] Whether it doesn't exist
#
def has_no_button?(locator = nil, **options, &optional_filter_block)
has_no_selector?(:button, locator, **options, &optional_filter_block)
end
##
#
# Checks if the page or current node has a form field with the given
# label, name or id.
#
# For text fields and other textual fields, such as textareas and
# HTML5 email/url/etc. fields, it's possible to specify a `:with`
# option to specify the text the field should contain:
#
# page.has_field?('Name', with: 'Jonas')
#
# It is also possible to filter by the field type attribute:
#
# page.has_field?('Email', type: 'email')
#
# NOTE: 'textarea' and 'select' are valid type values, matching the associated tag names.
#
# @param [String] locator The label, name or id of a field to check for
# @option options [String, Regexp] :with The text content of the field or a Regexp to match
# @option options [String] :type The type attribute of the field
# @return [Boolean] Whether it exists
#
def has_field?(locator = nil, **options, &optional_filter_block)
has_selector?(:field, locator, **options, &optional_filter_block)
end
##
#
# Checks if the page or current node has no form field with the given
# label, name or id. See {#has_field?}.
#
# @param [String] locator The label, name or id of a field to check for
# @option options [String, Regexp] :with The text content of the field or a Regexp to match
# @option options [String] :type The type attribute of the field
# @return [Boolean] Whether it doesn't exist
#
def has_no_field?(locator = nil, **options, &optional_filter_block)
has_no_selector?(:field, locator, **options, &optional_filter_block)
end
##
#
# Checks if the page or current node has a radio button or
# checkbox with the given label, value, id, or {Capybara.configure test_id} attribute that is currently
# checked.
#
# @param [String] locator The label, name or id of a checked field
# @return [Boolean] Whether it exists
#
def has_checked_field?(locator = nil, **options, &optional_filter_block)
has_selector?(:field, locator, **options.merge(checked: true), &optional_filter_block)
end
##
#
# Checks if the page or current node has no radio button or
# checkbox with the given label, value or id, or {Capybara.configure test_id} attribute that is currently
# checked.
#
# @param [String] locator The label, name or id of a checked field
# @return [Boolean] Whether it doesn't exist
#
def has_no_checked_field?(locator = nil, **options, &optional_filter_block)
has_no_selector?(:field, locator, **options.merge(checked: true), &optional_filter_block)
end
##
#
# Checks if the page or current node has a radio button or
# checkbox with the given label, value or id, or {Capybara.configure test_id} attribute that is currently
# unchecked.
#
# @param [String] locator The label, name or id of an unchecked field
# @return [Boolean] Whether it exists
#
def has_unchecked_field?(locator = nil, **options, &optional_filter_block)
has_selector?(:field, locator, **options.merge(unchecked: true), &optional_filter_block)
end
##
#
# Checks if the page or current node has no radio button or
# checkbox with the given label, value or id, or {Capybara.configure test_id} attribute that is currently
# unchecked.
#
# @param [String] locator The label, name or id of an unchecked field
# @return [Boolean] Whether it doesn't exist
#
def has_no_unchecked_field?(locator = nil, **options, &optional_filter_block)
has_no_selector?(:field, locator, **options.merge(unchecked: true), &optional_filter_block)
end
##
#
# Checks if the page or current node has a select field with the
# given label, name or id.
#
# It can be specified which option should currently be selected:
#
# page.has_select?('Language', selected: 'German')
#
# For multiple select boxes, several options may be specified:
#
# page.has_select?('Language', selected: ['English', 'German'])
#
# It's also possible to check if the exact set of options exists for
# this select box:
#
# page.has_select?('Language', options: ['English', 'German', 'Spanish'])
#
# You can also check for a partial set of options:
#
# page.has_select?('Language', with_options: ['English', 'German'])
#
# @param [String] locator The label, name or id of a select box
# @option options [Array] :options Options which should be contained in this select box
# @option options [Array] :with_options Partial set of options which should be contained in this select box
# @option options [String, Array] :selected Options which should be selected
# @option options [String, Array] :with_selected Partial set of options which should minimally be selected
# @return [Boolean] Whether it exists
#
def has_select?(locator = nil, **options, &optional_filter_block)
has_selector?(:select, locator, **options, &optional_filter_block)
end
##
#
# Checks if the page or current node has no select field with the
# given label, name or id. See {#has_select?}.
#
# @param (see #has_select?)
# @return [Boolean] Whether it doesn't exist
#
def has_no_select?(locator = nil, **options, &optional_filter_block)
has_no_selector?(:select, locator, **options, &optional_filter_block)
end
##
#
# Checks if the page or current node has a table with the given id
# or caption:
#
# page.has_table?('People')
#
# @param [String] locator The id or caption of a table
# @option options [Array<Array<String>>] :rows
# Text which should be contained in the tables `<td>` elements organized by row (`<td>` visibility is not considered)
# @option options [Array<Array<String>>, Array<Hash<String,String>>] :with_rows
# Partial set of text which should be contained in the tables `<td>` elements organized by row (`<td>` visibility is not considered)
# @option options [Array<Array<String>>] :cols
# Text which should be contained in the tables `<td>` elements organized by column (`<td>` visibility is not considered)
# @option options [Array<Array<String>>, Array<Hash<String,String>>] :with_cols
# Partial set of text which should be contained in the tables `<td>` elements organized by column (`<td>` visibility is not considered)
# @return [Boolean] Whether it exists
#
def has_table?(locator = nil, **options, &optional_filter_block)
has_selector?(:table, locator, **options, &optional_filter_block)
end
##
#
# Checks if the page or current node has no table with the given id
# or caption. See {#has_table?}.
#
# @param (see #has_table?)
# @return [Boolean] Whether it doesn't exist
#
def has_no_table?(locator = nil, **options, &optional_filter_block)
has_no_selector?(:table, locator, **options, &optional_filter_block)
end
##
#
# Asserts that the current node matches a given selector.
#
# node.assert_matches_selector('p#foo')
# node.assert_matches_selector(:xpath, '//p[@id="foo"]')
# node.assert_matches_selector(:foo)
#
# It also accepts all options that {Capybara::Node::Finders#all} accepts,
# such as `:text` and `:visible`.
#
# node.assert_matches_selector('li', text: 'Horse', visible: true)
#
# @param (see Capybara::Node::Finders#all)
# @raise [Capybara::ExpectationNotMet] If the selector does not match
#
def assert_matches_selector(*args, &optional_filter_block)
_verify_match_result(args, optional_filter_block) do |result|
raise Capybara::ExpectationNotMet, 'Item does not match the provided selector' unless result.include? self
end
end
##
#
# Asserts that the current node does not match a given selector.
# Usage is identical to {#assert_matches_selector}.
#
# @param (see #assert_matches_selector)
# @raise [Capybara::ExpectationNotMet] If the selector matches
#
def assert_not_matches_selector(*args, &optional_filter_block)
_verify_match_result(args, optional_filter_block) do |result|
raise Capybara::ExpectationNotMet, 'Item matched the provided selector' if result.include? self
end
end
##
#
# Checks if the current node matches given selector.
#
# @param (see #has_selector?)
# @return [Boolean]
#
def matches_selector?(*args, **options, &optional_filter_block)
make_predicate(options) { assert_matches_selector(*args, options, &optional_filter_block) }
end
##
#
# Checks if the current node matches given XPath expression.
#
# @param [String, XPath::Expression] xpath The XPath expression to match against the current code
# @return [Boolean]
#
def matches_xpath?(xpath, **options, &optional_filter_block)
matches_selector?(:xpath, xpath, **options, &optional_filter_block)
end
##
#
# Checks if the current node matches given CSS selector.
#
# @param [String] css The CSS selector to match against the current code
# @return [Boolean]
#
def matches_css?(css, **options, &optional_filter_block)
matches_selector?(:css, css, **options, &optional_filter_block)
end
##
#
# Checks if the current node does not match given selector.
# Usage is identical to {#has_selector?}.
#
# @param (see #has_selector?)
# @return [Boolean]
#
def not_matches_selector?(*args, **options, &optional_filter_block)
make_predicate(options) { assert_not_matches_selector(*args, options, &optional_filter_block) }
end
##
#
# Checks if the current node does not match given XPath expression.
#
# @param [String, XPath::Expression] xpath The XPath expression to match against the current code
# @return [Boolean]
#
def not_matches_xpath?(xpath, **options, &optional_filter_block)
not_matches_selector?(:xpath, xpath, **options, &optional_filter_block)
end
##
#
# Checks if the current node does not match given CSS selector.
#
# @param [String] css The CSS selector to match against the current code
# @return [Boolean]
#
def not_matches_css?(css, **options, &optional_filter_block)
not_matches_selector?(:css, css, **options, &optional_filter_block)
end
##
# Asserts that the page or current node has the given text content,
# ignoring any HTML tags.
#
# @!macro text_query_params
# @overload $0(type, text, **options)
# @param [:all, :visible] type Whether to check for only visible or all text. If this parameter is missing or nil then we use the value of {Capybara.configure ignore_hidden_elements}, which defaults to `true`, corresponding to `:visible`.
# @param [String, Regexp] text The string/regexp to check for. If it's a string, text is expected to include it. If it's a regexp, text is expected to match it.
# @option options [Integer] :count (nil) Number of times the text is expected to occur
# @option options [Integer] :minimum (nil) Minimum number of times the text is expected to occur
# @option options [Integer] :maximum (nil) Maximum number of times the text is expected to occur
# @option options [Range] :between (nil) Range of times that is expected to contain number of times text occurs
# @option options [Numeric] :wait Maximum time that Capybara will wait for text to eq/match given string/regexp argument. Defaults to {Capybara.configure default_max_wait_time}.
# @option options [Boolean] :exact Whether text must be an exact match or just substring. Defaults to {Capybara.configure exact_text}.
# @option options [Boolean] :normalize_ws (false) When `true` replace all whitespace with standard spaces and collapse consecutive whitespace to a single space
# @overload $0(text, **options)
# @param [String, Regexp] text The string/regexp to check for. If it's a string, text is expected to include it. If it's a regexp, text is expected to match it.
# @option options [Integer] :count (nil) Number of times the text is expected to occur
# @option options [Integer] :minimum (nil) Minimum number of times the text is expected to occur
# @option options [Integer] :maximum (nil) Maximum number of times the text is expected to occur
# @option options [Range] :between (nil) Range of times that is expected to contain number of times text occurs
# @option options [Numeric] :wait Maximum time that Capybara will wait for text to eq/match given string/regexp argument. Defaults to {Capybara.configure default_max_wait_time}.
# @option options [Boolean] :exact Whether text must be an exact match or just substring. Defaults to {Capybara.configure exact_text}.
# @option options [Boolean] :normalize_ws (false) When `true` replace all whitespace with standard spaces and collapse consecutive whitespace to a single space
# @raise [Capybara::ExpectationNotMet] if the assertion hasn't succeeded during wait time
# @return [true]
#
def assert_text(type_or_text, *args, **opts)
_verify_text(type_or_text, *args, **opts) do |count, query|
unless query.matches_count?(count) && (count.positive? || query.expects_none?)
raise Capybara::ExpectationNotMet, query.failure_message
end
end
end
##
# Asserts that the page or current node doesn't have the given text content,
# ignoring any HTML tags.
#
# @macro text_query_params
# @raise [Capybara::ExpectationNotMet] if the assertion hasn't succeeded during wait time
# @return [true]
#
def assert_no_text(type_or_text, *args, **opts)
_verify_text(type_or_text, *args, **opts) do |count, query|
if query.matches_count?(count) && (count.positive? || query.expects_none?)
raise Capybara::ExpectationNotMet, query.negative_failure_message
end
end
end
##
# Checks if the page or current node has the given text content,
# ignoring any HTML tags.
#
# By default it will check if the text occurs at least once,
# but a different number can be specified.
#
# page.has_text?('lorem ipsum', between: 2..4)
#
# This will check if the text occurs from 2 to 4 times.
#
# @macro text_query_params
# @return [Boolean] Whether it exists
#
def has_text?(*args, **options)
make_predicate(options) { assert_text(*args, **options) }
end
alias_method :has_content?, :has_text?
##
# Checks if the page or current node does not have the given text
# content, ignoring any HTML tags and normalizing whitespace.
#
# @macro text_query_params
# @return [Boolean] Whether it doesn't exist
#
def has_no_text?(*args, **options)
make_predicate(options) { assert_no_text(*args, **options) }
end
alias_method :has_no_content?, :has_no_text?
##
#
# Asserts that a given selector matches an ancestor of the current node.
#
# element.assert_ancestor('p#foo')
#
# Accepts the same options as {#assert_selector}
#
| ruby | MIT | b3325b198464b806f07ec2011ceb532d6d5cf4ab | 2026-01-04T15:38:10.098638Z | true |
teamcapybara/capybara | https://github.com/teamcapybara/capybara/blob/b3325b198464b806f07ec2011ceb532d6d5cf4ab/lib/capybara/node/finders.rb | lib/capybara/node/finders.rb | # frozen_string_literal: true
module Capybara
module Node
module Finders
##
#
# Find an {Capybara::Node::Element} based on the given arguments. {#find} will raise an error if the element
# is not found.
#
# page.find('#foo').find('.bar')
# page.find(:xpath, './/div[contains(., "bar")]')
# page.find('li', text: 'Quox').click_link('Delete')
#
# @param (see #all)
#
# @macro waiting_behavior
#
# @!macro system_filters
# @option options [String, Regexp] text Only find elements which contain this text or match this regexp
# @option options [String, Regexp, String] exact_text
# When String the elements contained text must match exactly, when Boolean controls whether the `text` option must match exactly.
# Defaults to {Capybara.configure exact_text}.
# @option options [Boolean] normalize_ws
# Whether the `text`/`exact_text` options are compared against element text with whitespace normalized or as returned by the driver.
# Defaults to {Capybara.configure default_normalize_ws}.
# @option options [Boolean, Symbol] visible
# Only find elements with the specified visibility. Defaults to behavior indicated by {Capybara.configure ignore_hidden_elements}.
# * true - only finds visible elements.
# * false - finds invisible _and_ visible elements.
# * :all - same as false; finds visible and invisible elements.
# * :hidden - only finds invisible elements.
# * :visible - same as true; only finds visible elements.
# @option options [Boolean] obscured Only find elements with the specified obscured state:
# * true - only find elements whose centerpoint is not in the viewport or is obscured by another non-descendant element.
# * false - only find elements whose centerpoint is in the viewport and is not obscured by other non-descendant elements.
# @option options [String, Regexp] id Only find elements with an id that matches the value passed
# @option options [String, Array<String>, Regexp] class Only find elements with matching class/classes.
# * Absence of a class can be checked by prefixing the class name with `!`
# * If you need to check for existence of a class name that starts with `!` then prefix with `!!`
#
# class:['a', '!b', '!!!c'] # limit to elements with class 'a' and '!c' but not class 'b'
#
# @option options [String, Regexp, Hash] style Only find elements with matching style. String and Regexp will be checked against text of the elements `style` attribute, while a Hash will be compared against the elements full style
# @option options [Boolean] exact Control whether `is` expressions in the given XPath match exactly or partially. Defaults to {Capybara.configure exact}.
# @option options [Symbol] match The matching strategy to use. Defaults to {Capybara.configure match}.
#
# @return [Capybara::Node::Element] The found element
# @raise [Capybara::ElementNotFound] If the element can't be found before time expires
#
def find(*args, **options, &optional_filter_block)
options[:session_options] = session_options
count_options = options.slice(*Capybara::Queries::BaseQuery::COUNT_KEYS)
unless count_options.empty?
Capybara::Helpers.warn(
"'find' does not support count options (#{count_options}) ignoring. " \
"Called from: #{Capybara::Helpers.filter_backtrace(caller)}"
)
end
synced_resolve Capybara::Queries::SelectorQuery.new(*args, **options, &optional_filter_block)
end
##
#
# Find an {Capybara::Node::Element} based on the given arguments that is also an ancestor of the element called on.
# {#ancestor} will raise an error if the element is not found.
#
# {#ancestor} takes the same options as {#find}.
#
# element.ancestor('#foo').find('.bar')
# element.ancestor(:xpath, './/div[contains(., "bar")]')
# element.ancestor('ul', text: 'Quox').click_link('Delete')
#
# @param (see #find)
#
# @macro waiting_behavior
#
# @return [Capybara::Node::Element] The found element
# @raise [Capybara::ElementNotFound] If the element can't be found before time expires
#
def ancestor(*args, **options, &optional_filter_block)
options[:session_options] = session_options
synced_resolve Capybara::Queries::AncestorQuery.new(*args, **options, &optional_filter_block)
end
##
#
# Find an {Capybara::Node::Element} based on the given arguments that is also a sibling of the element called on.
# {#sibling} will raise an error if the element is not found.
#
# {#sibling} takes the same options as {#find}.
#
# element.sibling('#foo').find('.bar')
# element.sibling(:xpath, './/div[contains(., "bar")]')
# element.sibling('ul', text: 'Quox').click_link('Delete')
#
# @param (see #find)
#
# @macro waiting_behavior
#
# @return [Capybara::Node::Element] The found element
# @raise [Capybara::ElementNotFound] If the element can't be found before time expires
#
def sibling(*args, **options, &optional_filter_block)
options[:session_options] = session_options
synced_resolve Capybara::Queries::SiblingQuery.new(*args, **options, &optional_filter_block)
end
##
#
# Find a form field on the page. The field can be found by its name, id or label text.
#
# @overload find_field([locator], **options)
# @param [String] locator name, id, {Capybara.configure test_id} attribute, placeholder or text of associated label element
#
# @macro waiting_behavior
#
#
# @option options [Boolean] checked Match checked field?
# @option options [Boolean] unchecked Match unchecked field?
# @option options [Boolean, Symbol] disabled (false) Match disabled field?
# * true - only finds a disabled field
# * false - only finds an enabled field
# * :all - finds either an enabled or disabled field
# @option options [Boolean] readonly Match readonly field?
# @option options [String, Regexp] with Value of field to match on
# @option options [String] type Type of field to match on
# @option options [Boolean] multiple Match fields that can have multiple values?
# @option options [String, Regexp] id Match fields that match the id attribute
# @option options [String] name Match fields that match the name attribute
# @option options [String] placeholder Match fields that match the placeholder attribute
# @option options [String, Array<String>, Regexp] class Match fields that match the class(es) passed
# @return [Capybara::Node::Element] The found element
#
def find_field(locator = nil, **options, &optional_filter_block)
find(:field, locator, **options, &optional_filter_block)
end
##
#
# Find a link on the page. The link can be found by its id or text.
#
# @overload find_link([locator], **options)
# @param [String] locator id, {Capybara.configure test_id} attribute, title, text, or alt of enclosed img element
#
# @macro waiting_behavior
#
# @option options [String,Regexp,nil] href Value to match against the links href, if `nil` finds link placeholders (`<a>` elements with no href attribute), if `false` ignores the href
# @option options [String, Regexp] id Match links with the id provided
# @option options [String] title Match links with the title provided
# @option options [String] alt Match links with a contained img element whose alt matches
# @option options [String, Boolean] download Match links with the download provided
# @option options [String] target Match links with the target provided
# @option options [String, Array<String>, Regexp] class Match links that match the class(es) provided
# @return [Capybara::Node::Element] The found element
#
def find_link(locator = nil, **options, &optional_filter_block)
find(:link, locator, **options, &optional_filter_block)
end
##
#
# Find a button on the page.
# This can be any `<input>` element of type submit, reset, image, button or it can be a
# `<button>` element. All buttons can be found by their id, name, {Capybara.configure test_id} attribute, value, or title.
# `<button>` elements can also be found by their text content, and image `<input>` elements by their alt attribute.
#
# @overload find_button([locator], **options)
# @param [String] locator id, name, {Capybara.configure test_id} attribute, value, title, text content, alt of image
#
# @macro waiting_behavior
#
# @option options [Boolean, Symbol] disabled (false) Match disabled button?
# * true - only finds a disabled button
# * false - only finds an enabled button
# * :all - finds either an enabled or disabled button
# @option options [String, Regexp] id Match buttons with the id provided
# @option options [String] name Match buttons with the name provided
# @option options [String] title Match buttons with the title provided
# @option options [String] value Match buttons with the value provided
# @option options [String, Array<String>, Regexp] class Match buttons that match the class(es) provided
# @return [Capybara::Node::Element] The found element
#
def find_button(locator = nil, **options, &optional_filter_block)
find(:button, locator, **options, &optional_filter_block)
end
##
#
# Find a element on the page, given its id.
#
# @macro waiting_behavior
#
# @param [String] id id of element
#
# @return [Capybara::Node::Element] The found element
#
def find_by_id(id, **options, &optional_filter_block)
find(:id, id, **options, &optional_filter_block)
end
##
# @!method all([kind = Capybara.default_selector], locator = nil, **options)
#
# Find all elements on the page matching the given selector
# and options.
#
# Both XPath and CSS expressions are supported, but Capybara
# does not try to automatically distinguish between them. The
# following statements are equivalent:
#
# page.all(:css, 'a#person_123')
# page.all(:xpath, './/a[@id="person_123"]')
#
# If the type of selector is left out, Capybara uses
# {Capybara.configure default_selector}. It's set to `:css` by default.
#
# page.all("a#person_123")
#
# Capybara.default_selector = :xpath
# page.all('.//a[@id="person_123"]')
#
# The set of found elements can further be restricted by specifying
# options. It's possible to select elements by their text or visibility:
#
# page.all('a', text: 'Home')
# page.all('#menu li', visible: true)
#
# By default Capybara's waiting behavior will wait up to {Capybara.configure default_max_wait_time}
# seconds for matching elements to be available and then return an empty result if none
# are available. It is possible to set expectations on the number of results located and
# Capybara will raise an exception if the number of elements located don't satisfy the
# specified conditions. The expectations can be set using:
#
# page.assert_selector('p#foo', count: 4)
# page.assert_selector('p#foo', maximum: 10)
# page.assert_selector('p#foo', minimum: 1)
# page.assert_selector('p#foo', between: 1..10)
#
# @param [Symbol] kind Optional selector type (:css, :xpath, :field, etc.). Defaults to {Capybara.configure default_selector}.
# @param [String] locator The locator for the specified selector
# @macro system_filters
# @macro waiting_behavior
# @option options [Integer] count Exact number of matches that are expected to be found
# @option options [Integer] maximum Maximum number of matches that are expected to be found
# @option options [Integer] minimum Minimum number of matches that are expected to be found
# @option options [Range] between Number of matches found must be within the given range
# @option options [Boolean] allow_reload Beta feature - May be removed in any version.
# When `true` allows elements to be reloaded if they become stale. This is an advanced behavior and should only be used
# if you fully understand the potential ramifications. The results can be confusing on dynamic pages. Defaults to `false`
# @overload all([kind = Capybara.default_selector], locator = nil, **options)
# @overload all([kind = Capybara.default_selector], locator = nil, **options, &filter_block)
# @yieldparam element [Capybara::Node::Element] The element being considered for inclusion in the results
# @yieldreturn [Boolean] Should the element be considered in the results?
# @return [Capybara::Result] A collection of found elements
# @raise [Capybara::ExpectationNotMet] The number of elements found doesn't match the specified conditions
def all(*args, allow_reload: false, **options, &optional_filter_block)
minimum_specified = options_include_minimum?(options)
options = { minimum: 1 }.merge(options) unless minimum_specified
options[:session_options] = session_options
query = Capybara::Queries::SelectorQuery.new(*args, **options, &optional_filter_block)
result = nil
begin
synchronize(query.wait) do
result = query.resolve_for(self)
result.allow_reload! if allow_reload
raise Capybara::ExpectationNotMet, result.failure_message unless result.matches_count?
result
end
rescue Capybara::ExpectationNotMet
raise if minimum_specified || (result.compare_count == 1)
Result.new([], nil)
end
end
alias_method :find_all, :all
##
#
# Find the first element on the page matching the given selector
# and options. By default {#first} will wait up to {Capybara.configure default_max_wait_time}
# seconds for matching elements to appear and then raise an error if no matching
# element is found, or `nil` if the provided count options allow for empty results.
#
# @overload first([kind], locator, options)
# @param [Symbol] kind The type of selector
# @param [String] locator The selector
# @param [Hash] options Additional options; see {#all}
# @return [Capybara::Node::Element] The found element or nil
# @raise [Capybara::ElementNotFound] If element(s) matching the provided options can't be found before time expires
#
def first(*args, **options, &optional_filter_block)
options = { minimum: 1 }.merge(options) unless options_include_minimum?(options)
all(*args, **options, &optional_filter_block).first
end
private
def synced_resolve(query)
synchronize(query.wait) do
if prefer_exact?(query)
result = query.resolve_for(self, true)
result = query.resolve_for(self, false) if result.empty? && query.supports_exact? && !query.exact?
else
result = query.resolve_for(self)
end
if ambiguous?(query, result)
raise Capybara::Ambiguous, "Ambiguous match, found #{result.size} elements matching #{query.applied_description}"
end
raise Capybara::ElementNotFound, "Unable to find #{query.applied_description}" if result.empty?
result.first
end.tap(&:allow_reload!)
end
def ambiguous?(query, result)
%i[one smart].include?(query.match) && (result.size > 1)
end
def prefer_exact?(query)
%i[smart prefer_exact].include?(query.match)
end
def options_include_minimum?(opts)
%i[count minimum between].any? { |key| opts.key?(key) }
end
def parent
first(:xpath, './parent::*', minimum: 0)
end
end
end
end
| ruby | MIT | b3325b198464b806f07ec2011ceb532d6d5cf4ab | 2026-01-04T15:38:10.098638Z | false |
teamcapybara/capybara | https://github.com/teamcapybara/capybara/blob/b3325b198464b806f07ec2011ceb532d6d5cf4ab/lib/capybara/node/whitespace_normalizer.rb | lib/capybara/node/whitespace_normalizer.rb | # frozen_string_literal: true
module Capybara
module Node
##
#
# {Capybara::Node::WhitespaceNormalizer} provides methods that
# help to normalize the spacing of text content inside of
# {Capybara::Node::Element}s by removing various unicode
# spacing and directional markings.
#
module WhitespaceNormalizer
# Unicode for NBSP, or
NON_BREAKING_SPACE = "\u00a0"
LINE_SEPERATOR = "\u2028"
PARAGRAPH_SEPERATOR = "\u2029"
# All spaces except for NBSP
BREAKING_SPACES = "[[:space:]&&[^#{NON_BREAKING_SPACE}]]".freeze
# Whitespace we want to substitute with plain spaces
SQUEEZED_SPACES = " \n\f\t\v#{LINE_SEPERATOR}#{PARAGRAPH_SEPERATOR}".freeze
# Any whitespace at the front of text
LEADING_SPACES = /\A#{BREAKING_SPACES}+/
# Any whitespace at the end of text
TRAILING_SPACES = /#{BREAKING_SPACES}+\z/
# "Invisible" space character
ZERO_WIDTH_SPACE = "\u200b"
# Signifies text is read left to right
LEFT_TO_RIGHT_MARK = "\u200e"
# Signifies text is read right to left
RIGHT_TO_LEFT_MARK = "\u200f"
# Characters we want to truncate from text
REMOVED_CHARACTERS = [ZERO_WIDTH_SPACE, LEFT_TO_RIGHT_MARK, RIGHT_TO_LEFT_MARK].join
# Matches multiple empty lines
EMPTY_LINES = /[\ \n]*\n[\ \n]*/
##
#
# Normalizes the spacing of a node's text to be similar to
# what matchers might expect.
#
# @param text [String]
# @return [String]
#
def normalize_spacing(text)
text
.delete(REMOVED_CHARACTERS)
.tr(SQUEEZED_SPACES, ' ')
.squeeze(' ')
.sub(LEADING_SPACES, '')
.sub(TRAILING_SPACES, '')
.tr(NON_BREAKING_SPACE, ' ')
end
##
#
# Variant on {Capybara::Node::Normalizer#normalize_spacing} that
# targets the whitespace of visible elements only.
#
# @param text [String]
# @return [String]
#
def normalize_visible_spacing(text)
text
.squeeze(' ')
.gsub(EMPTY_LINES, "\n")
.sub(LEADING_SPACES, '')
.sub(TRAILING_SPACES, '')
.tr(NON_BREAKING_SPACE, ' ')
end
end
end
end
| ruby | MIT | b3325b198464b806f07ec2011ceb532d6d5cf4ab | 2026-01-04T15:38:10.098638Z | false |
teamcapybara/capybara | https://github.com/teamcapybara/capybara/blob/b3325b198464b806f07ec2011ceb532d6d5cf4ab/lib/capybara/node/base.rb | lib/capybara/node/base.rb | # frozen_string_literal: true
module Capybara
module Node
##
#
# A {Capybara::Node::Base} represents either an element on a page through the subclass
# {Capybara::Node::Element} or a document through {Capybara::Node::Document}.
#
# Both types of Node share the same methods, used for interacting with the
# elements on the page. These methods are divided into three categories,
# finders, actions and matchers. These are found in the modules
# {Capybara::Node::Finders}, {Capybara::Node::Actions} and {Capybara::Node::Matchers}
# respectively.
#
# A {Capybara::Session} exposes all methods from {Capybara::Node::Document} directly:
#
# session = Capybara::Session.new(:rack_test, my_app)
# session.visit('/')
# session.fill_in('Foo', with: 'Bar') # from Capybara::Node::Actions
# bar = session.find('#bar') # from Capybara::Node::Finders
# bar.select('Baz', from: 'Quox') # from Capybara::Node::Actions
# session.has_css?('#foobar') # from Capybara::Node::Matchers
#
class Base
attr_reader :session, :base, :query_scope
include Capybara::Node::Finders
include Capybara::Node::Actions
include Capybara::Node::Matchers
def initialize(session, base)
@session = session
@base = base
end
# overridden in subclasses, e.g. Capybara::Node::Element
def reload
self
end
##
#
# This method is Capybara's primary defence against asynchronicity
# problems. It works by attempting to run a given block of code until it
# succeeds. The exact behaviour of this method depends on a number of
# factors. Basically there are certain exceptions which, when raised
# from the block, instead of bubbling up, are caught, and the block is
# re-run.
#
# Certain drivers, such as RackTest, have no support for asynchronous
# processes, these drivers run the block, and any error raised bubbles up
# immediately. This allows faster turn around in the case where an
# expectation fails.
#
# Only exceptions that are {Capybara::ElementNotFound} or any subclass
# thereof cause the block to be rerun. Drivers may specify additional
# exceptions which also cause reruns. This usually occurs when a node is
# manipulated which no longer exists on the page. For example, the
# Selenium driver specifies
# `Selenium::WebDriver::Error::ObsoleteElementError`.
#
# As long as any of these exceptions are thrown, the block is re-run,
# until a certain amount of time passes. The amount of time defaults to
# {Capybara.default_max_wait_time} and can be overridden through the `seconds`
# argument. This time is compared with the system time to see how much
# time has passed. On rubies/platforms which don't support access to a monotonic process clock
# if the return value of `Time.now` is stubbed out, Capybara will raise `Capybara::FrozenInTime`.
#
# @param [Integer] seconds (current sessions default_max_wait_time) Maximum number of seconds to retry this block
# @param [Array<Exception>] errors (driver.invalid_element_errors +
# [Capybara::ElementNotFound]) exception types that cause the block to be rerun
# @return [Object] The result of the given block
# @raise [Capybara::FrozenInTime] If the return value of `Time.now` appears stuck
#
def synchronize(seconds = nil, errors: nil)
return yield if session.synchronized
seconds = session_options.default_max_wait_time if [nil, true].include? seconds
interval = session_options.default_retry_interval
session.synchronized = true
timer = Capybara::Helpers.timer(expire_in: seconds)
begin
yield
rescue StandardError => e
session.raise_server_error!
raise e unless catch_error?(e, errors)
if driver.wait?
raise e if timer.expired?
sleep interval
reload if session_options.automatic_reload
else
old_base = @base
reload if session_options.automatic_reload
raise e if old_base == @base
end
retry
ensure
session.synchronized = false
end
end
# @api private
def find_css(css, **options)
if base.method(:find_css).arity == 1
base.find_css(css)
else
base.find_css(css, **options)
end
end
# @api private
def find_xpath(xpath, **options)
if base.method(:find_xpath).arity == 1
base.find_xpath(xpath)
else
base.find_xpath(xpath, **options)
end
end
# @api private
def session_options
session.config
end
def to_capybara_node
self
end
protected
def catch_error?(error, errors = nil)
errors ||= (driver.invalid_element_errors + [Capybara::ElementNotFound])
errors.any? { |type| error.is_a?(type) }
end
def driver
session.driver
end
end
end
end
| ruby | MIT | b3325b198464b806f07ec2011ceb532d6d5cf4ab | 2026-01-04T15:38:10.098638Z | false |
teamcapybara/capybara | https://github.com/teamcapybara/capybara/blob/b3325b198464b806f07ec2011ceb532d6d5cf4ab/lib/capybara/node/simple.rb | lib/capybara/node/simple.rb | # frozen_string_literal: true
module Capybara
module Node
##
#
# A {Capybara::Node::Simple} is a simpler version of {Capybara::Node::Base} which
# includes only {Capybara::Node::Finders} and {Capybara::Node::Matchers} and does
# not include {Capybara::Node::Actions}. This type of node is returned when
# using {Capybara.string}.
#
# It is useful in that it does not require a session, an application or a driver,
# but can still use Capybara's finders and matchers on any string that contains HTML.
#
class Simple
include Capybara::Node::Finders
include Capybara::Node::Matchers
include Capybara::Node::DocumentMatchers
attr_reader :native
def initialize(native)
native = Capybara::HTML(native) if native.is_a?(String)
@native = native
end
##
#
# @return [String] The text of the element
#
def text(_type = nil, normalize_ws: false)
txt = native.text
normalize_ws ? txt.gsub(/[[:space:]]+/, ' ').strip : txt
end
##
#
# Retrieve the given attribute
#
# element[:title] # => HTML title attribute
#
# @param [Symbol] name The attribute name to retrieve
# @return [String] The value of the attribute
#
def [](name)
attr_name = name.to_s
if attr_name == 'value'
value
elsif (tag_name == 'input') && (native[:type] == 'checkbox') && (attr_name == 'checked')
native['checked'] == 'checked'
else
native[attr_name]
end
end
##
#
# @return [String] The tag name of the element
#
def tag_name
native.node_name
end
##
#
# An XPath expression describing where on the page the element can be found
#
# @return [String] An XPath expression
#
def path
native.path
end
##
#
# @return [String] The value of the form element
#
def value
if tag_name == 'textarea'
native['_capybara_raw_value']
elsif tag_name == 'select'
selected_options = find_xpath('.//option[@selected]')
if multiple?
selected_options.map(&method(:option_value))
else
option_value(selected_options.first || find_xpath('.//option').first)
end
elsif tag_name == 'input' && %w[radio checkbox].include?(native[:type])
native[:value] || 'on'
else
native[:value]
end
end
##
#
# Whether or not the element is visible. Does not support CSS, so
# the result may be inaccurate.
#
# @param [Boolean] check_ancestors Whether to inherit visibility from ancestors
# @return [Boolean] Whether the element is visible
#
def visible?(check_ancestors = true) # rubocop:disable Style/OptionalBooleanParameter
return false if (tag_name == 'input') && (native[:type] == 'hidden')
return false if tag_name == 'template'
if check_ancestors
!find_xpath(VISIBILITY_XPATH)
else
# No need for an xpath if only checking the current element
!(native.key?('hidden') ||
/display:\s?none/.match?(native[:style] || '') ||
%w[script head style].include?(tag_name))
end
end
##
#
# Whether or not the element is checked.
#
# @return [Boolean] Whether the element is checked
#
def checked?
native.has_attribute?('checked')
end
##
#
# Whether or not the element is disabled.
#
# @return [Boolean] Whether the element is disabled
def disabled?
native.has_attribute?('disabled') &&
%w[button input select textarea optgroup option menuitem fieldset].include?(tag_name)
end
##
#
# Whether or not the element is selected.
#
# @return [Boolean] Whether the element is selected
#
def selected?
native.has_attribute?('selected')
end
def multiple?
native.has_attribute?('multiple')
end
def readonly?
native.has_attribute?('readonly')
end
def synchronize(_seconds = nil)
yield # simple nodes don't need to wait
end
def allow_reload!(*)
# no op
end
##
#
# @return [String] The title of the document
def title
native.title
end
def inspect
%(#<Capybara::Node::Simple tag="#{tag_name}" path="#{path}">)
end
# @api private
def find_css(css, **_options)
native.css(css)
end
# @api private
def find_xpath(xpath, **_options)
native.xpath(xpath)
end
# @api private
def session_options
Capybara.session_options
end
# @api private
def initial_cache
{}
end
def ==(other)
eql?(other) || (other.respond_to?(:native) && native == other.native)
end
private
def option_value(option)
return nil if option.nil?
option[:value] || option.content
end
VISIBILITY_XPATH = XPath.generate do |x|
x.ancestor_or_self[
x.attr(:style)[x.contains('display:none') | x.contains('display: none')] |
x.attr(:hidden) |
x.qname.one_of('script', 'head') |
(~x.self(:summary) & XPath.parent(:details)[!XPath.attr(:open)])
].boolean
end.to_s.freeze
end
end
end
| ruby | MIT | b3325b198464b806f07ec2011ceb532d6d5cf4ab | 2026-01-04T15:38:10.098638Z | false |
teamcapybara/capybara | https://github.com/teamcapybara/capybara/blob/b3325b198464b806f07ec2011ceb532d6d5cf4ab/lib/capybara/node/document_matchers.rb | lib/capybara/node/document_matchers.rb | # frozen_string_literal: true
module Capybara
module Node
module DocumentMatchers
##
# Asserts that the page has the given title.
#
# @!macro title_query_params
# @overload $0(string, **options)
# @param string [String] The string that title should include
# @overload $0(regexp, **options)
# @param regexp [Regexp] The regexp that title should match to
# @option options [Numeric] :wait (Capybara.default_max_wait_time) Maximum time that Capybara will wait for title to eq/match given string/regexp argument
# @option options [Boolean] :exact (false) When passed a string should the match be exact or just substring
# @raise [Capybara::ExpectationNotMet] if the assertion hasn't succeeded during wait time
# @return [true]
#
def assert_title(title, **options)
_verify_title(title, options) do |query|
raise Capybara::ExpectationNotMet, query.failure_message unless query.resolves_for?(self)
end
end
##
# Asserts that the page doesn't have the given title.
#
# @macro title_query_params
# @raise [Capybara::ExpectationNotMet] if the assertion hasn't succeeded during wait time
# @return [true]
#
def assert_no_title(title, **options)
_verify_title(title, options) do |query|
raise Capybara::ExpectationNotMet, query.negative_failure_message if query.resolves_for?(self)
end
end
##
# Checks if the page has the given title.
#
# @macro title_query_params
# @return [Boolean]
#
def has_title?(title, **options)
make_predicate(options) { assert_title(title, **options) }
end
##
# Checks if the page doesn't have the given title.
#
# @macro title_query_params
# @return [Boolean]
#
def has_no_title?(title, **options)
make_predicate(options) { assert_no_title(title, **options) }
end
private
def _verify_title(title, options)
query = Capybara::Queries::TitleQuery.new(title, **options)
synchronize(query.wait) { yield(query) }
true
end
end
end
end
| ruby | MIT | b3325b198464b806f07ec2011ceb532d6d5cf4ab | 2026-01-04T15:38:10.098638Z | false |
teamcapybara/capybara | https://github.com/teamcapybara/capybara/blob/b3325b198464b806f07ec2011ceb532d6d5cf4ab/lib/capybara/node/document.rb | lib/capybara/node/document.rb | # frozen_string_literal: true
module Capybara
module Node
##
#
# A {Capybara::Document} represents an HTML document. Any operation
# performed on it will be performed on the entire document.
#
# @see Capybara::Node
#
class Document < Base
include Capybara::Node::DocumentMatchers
def inspect
%(#<Capybara::Document>)
end
##
#
# @return [String] The text of the document
#
def text(type = nil, normalize_ws: false)
find(:xpath, '/html').text(type, normalize_ws: normalize_ws)
end
##
#
# @return [String] The title of the document
#
def title
session.driver.title
end
def execute_script(*args)
find(:xpath, '/html').execute_script(*args)
end
def evaluate_script(*args)
find(:xpath, '/html').evaluate_script(*args)
end
def scroll_to(*args, quirks: false, **options)
find(:xpath, quirks ? '//body' : '/html').scroll_to(*args, **options)
end
end
end
end
| ruby | MIT | b3325b198464b806f07ec2011ceb532d6d5cf4ab | 2026-01-04T15:38:10.098638Z | false |
teamcapybara/capybara | https://github.com/teamcapybara/capybara/blob/b3325b198464b806f07ec2011ceb532d6d5cf4ab/lib/capybara/registrations/servers.rb | lib/capybara/registrations/servers.rb | # frozen_string_literal: true
Capybara.register_server :default do |app, port, _host|
Capybara.run_default_server(app, port)
end
Capybara.register_server :webrick do |app, port, host, **options|
base_class = begin
require 'rack/handler/webrick'
Rack
rescue LoadError
# Rack 3 separated out the webrick handle - no way test currently in Capybaras automated
# tests due to Sinatra not yet supporting Rack 3 - experimental
require 'rackup/handler/webrick'
Rackup
end
options = { Host: host, Port: port, AccessLog: [], Logger: WEBrick::Log.new(nil, 0) }.merge(options)
base_class::Handler::WEBrick.run(app, **options)
end
Capybara.register_server :puma do |app, port, host, **options| # rubocop:disable Metrics/BlockLength
begin
require 'rackup'
rescue LoadError # rubocop:disable Lint/SuppressedException
end
begin
require 'rack/handler/puma'
rescue LoadError
raise LoadError, 'Capybara is unable to load `puma` for its server, please add `puma` to your project or specify a different server via something like `Capybara.server = :webrick`.'
end
puma_rack_handler = defined?(Rackup::Handler::Puma) ? Rackup::Handler::Puma : Rack::Handler::Puma
unless puma_rack_handler.respond_to?(:config)
raise LoadError, 'Capybara requires `puma` version 3.8.0 or higher, please upgrade `puma` or register and specify your own server block'
end
# If we just run the Puma Rack handler it installs signal handlers which prevent us from being able to interrupt tests.
# Therefore construct and run the Server instance ourselves.
# puma_rack_handler.run(app, { Host: host, Port: port, Threads: "0:4", workers: 0, daemon: false }.merge(options))
default_options = { Host: host, Port: port, Threads: '0:4', workers: 0, daemon: false }
options = default_options.merge(options)
conf = puma_rack_handler.config(app, options)
conf.clamp
puma_ver = Gem::Version.new(Puma::Const::PUMA_VERSION)
require_relative 'patches/puma_ssl' if Gem::Requirement.new('>=4.0.0', '< 4.1.0').satisfied_by?(puma_ver)
logger = (defined?(Puma::LogWriter) ? Puma::LogWriter : Puma::Events).then do |cls|
conf.options[:Silent] ? cls.strings : cls.stdio
end
conf.options[:log_writer] = logger
logger.log 'Capybara starting Puma...'
logger.log "* Version #{Puma::Const::PUMA_VERSION}, codename: #{Puma::Const::CODE_NAME}"
logger.log "* Min threads: #{conf.options[:min_threads]}, max threads: #{conf.options[:max_threads]}"
Puma::Server.new(
conf.app,
defined?(Puma::LogWriter) ? nil : logger,
conf.options
).tap do |s|
s.binder.parse conf.options[:binds], (s.log_writer rescue s.events) # rubocop:disable Style/RescueModifier
s.min_threads, s.max_threads = conf.options[:min_threads], conf.options[:max_threads] if s.respond_to? :min_threads=
end.run.join
end
| ruby | MIT | b3325b198464b806f07ec2011ceb532d6d5cf4ab | 2026-01-04T15:38:10.098638Z | false |
teamcapybara/capybara | https://github.com/teamcapybara/capybara/blob/b3325b198464b806f07ec2011ceb532d6d5cf4ab/lib/capybara/registrations/drivers.rb | lib/capybara/registrations/drivers.rb | # frozen_string_literal: true
Capybara.register_driver :rack_test do |app|
Capybara::RackTest::Driver.new(app)
end
Capybara.register_driver :selenium do |app|
Capybara::Selenium::Driver.new(app)
end
Capybara.register_driver :selenium_headless do |app|
version = Capybara::Selenium::Driver.load_selenium
options_key = Capybara::Selenium::Driver::CAPS_VERSION.satisfied_by?(version) ? :capabilities : :options
browser_options = Selenium::WebDriver::Firefox::Options.new.tap do |opts|
opts.add_argument '-headless'
end
Capybara::Selenium::Driver.new(app, **{ :browser => :firefox, options_key => browser_options })
end
Capybara.register_driver :selenium_chrome do |app|
version = Capybara::Selenium::Driver.load_selenium
options_key = Capybara::Selenium::Driver::CAPS_VERSION.satisfied_by?(version) ? :capabilities : :options
browser_options = Selenium::WebDriver::Chrome::Options.new.tap do |opts|
# Workaround https://bugs.chromium.org/p/chromedriver/issues/detail?id=2650&q=load&sort=-id&colspec=ID%20Status%20Pri%20Owner%20Summary
opts.add_argument('--disable-site-isolation-trials')
end
Capybara::Selenium::Driver.new(app, **{ :browser => :chrome, options_key => browser_options })
end
Capybara.register_driver :selenium_chrome_headless do |app|
version = Capybara::Selenium::Driver.load_selenium
options_key = Capybara::Selenium::Driver::CAPS_VERSION.satisfied_by?(version) ? :capabilities : :options
browser_options = Selenium::WebDriver::Chrome::Options.new.tap do |opts|
opts.add_argument('--headless=new')
opts.add_argument('--disable-gpu') if Gem.win_platform?
# Workaround https://bugs.chromium.org/p/chromedriver/issues/detail?id=2650&q=load&sort=-id&colspec=ID%20Status%20Pri%20Owner%20Summary
opts.add_argument('--disable-site-isolation-trials')
# https://github.com/teamcapybara/capybara/issues/2796#issuecomment-2678172710
opts.add_argument('disable-background-timer-throttling')
opts.add_argument('disable-backgrounding-occluded-windows')
opts.add_argument('disable-renderer-backgrounding')
end
Capybara::Selenium::Driver.new(app, **{ :browser => :chrome, options_key => browser_options })
end
| ruby | MIT | b3325b198464b806f07ec2011ceb532d6d5cf4ab | 2026-01-04T15:38:10.098638Z | false |
teamcapybara/capybara | https://github.com/teamcapybara/capybara/blob/b3325b198464b806f07ec2011ceb532d6d5cf4ab/lib/capybara/registrations/patches/puma_ssl.rb | lib/capybara/registrations/patches/puma_ssl.rb | # frozen_string_literal: true
module Puma
module MiniSSL
class Socket
def read_nonblock(size, *_)
wait_states = %i[wait_readable wait_writable]
loop do
output = engine_read_all
return output if output
data = @socket.read_nonblock(size, exception: false)
raise IO::EAGAINWaitReadable if wait_states.include? data
return nil if data.nil?
@engine.inject(data)
output = engine_read_all
return output if output
while (neg_data = @engine.extract)
@socket.write neg_data
end
end
end
end
end
end
| ruby | MIT | b3325b198464b806f07ec2011ceb532d6d5cf4ab | 2026-01-04T15:38:10.098638Z | false |
teamcapybara/capybara | https://github.com/teamcapybara/capybara/blob/b3325b198464b806f07ec2011ceb532d6d5cf4ab/lib/capybara/selector/selector.rb | lib/capybara/selector/selector.rb | # frozen_string_literal: true
module Capybara
class Selector < SimpleDelegator
class << self
def all
@definitions ||= {} # rubocop:disable Naming/MemoizedInstanceVariableName
end
def [](name)
all.fetch(name.to_sym) { |sel_type| raise ArgumentError, "Unknown selector type (:#{sel_type})" }
end
def add(name, **options, &block)
all[name.to_sym] = Definition.new(name.to_sym, **options, &block)
end
def update(name, &block)
self[name].instance_eval(&block)
end
def remove(name)
all.delete(name.to_sym)
end
def for(locator)
all.values.find { |sel| sel.match?(locator) }
end
end
attr_reader :errors
def initialize(definition, config:, format:)
definition = self.class[definition] unless definition.is_a? Definition
super(definition)
@definition = definition
@config = config
@format = format
@errors = []
end
def format
@format || @definition.default_format
end
alias_method :current_format, :format
def enable_aria_label
@config[:enable_aria_label]
end
def enable_aria_role
@config[:enable_aria_role]
end
def test_id
@config[:test_id]
end
def call(locator, **options)
if format
raise ArgumentError, "Selector #{@name} does not support #{format}" unless expressions.key?(format)
instance_exec(locator, **options, &expressions[format])
else
warn 'Selector has no format'
end
ensure
unless locator_valid?(locator)
Capybara::Helpers.warn(
"Locator #{locator.class}:#{locator.inspect} for selector #{name.inspect} must #{locator_description}. " \
'This will raise an error in a future version of Capybara. ' \
"Called from: #{Capybara::Helpers.filter_backtrace(caller)}"
)
end
end
def add_error(error_msg)
errors << error_msg
end
def expression_for(name, locator, config: @config, format: current_format, **options)
Selector.new(name, config: config, format: format).call(locator, **options)
end
# @api private
def with_filter_errors(errors)
old_errors = @errors
@errors = errors
yield
ensure
@errors = old_errors
end
# @api private
def builder(expr = nil)
case format
when :css
Capybara::Selector::CSSBuilder
when :xpath
Capybara::Selector::XPathBuilder
else
raise NotImplementedError, "No builder exists for selector of type #{default_format}"
end.new(expr)
end
private
def locator_description
locator_types.group_by { |lt| lt.is_a? Symbol }.map do |symbol, types_or_methods|
if symbol
"respond to #{types_or_methods.join(' or ')}"
else
"be an instance of #{types_or_methods.join(' or ')}"
end
end.join(' or ')
end
def locator_valid?(locator)
return true unless locator && locator_types
locator_types&.any? do |type_or_method|
type_or_method.is_a?(Symbol) ? locator.respond_to?(type_or_method) : type_or_method === locator # rubocop:disable Style/CaseEquality
end
end
def locate_field(xpath, locator, **_options)
return xpath if locator.nil?
locate_xpath = xpath # Need to save original xpath for the label wrap
locator = locator.to_s
attr_matchers = [XPath.attr(:id) == locator,
XPath.attr(:name) == locator,
XPath.attr(:placeholder) == locator,
XPath.attr(:id) == XPath.anywhere(:label)[XPath.string.n.is(locator)].attr(:for)].reduce(:|)
attr_matchers |= XPath.attr(:'aria-label').is(locator) if enable_aria_label
attr_matchers |= XPath.attr(test_id) == locator if test_id
locate_xpath = locate_xpath[attr_matchers]
locate_xpath + locate_label(locator).descendant(xpath)
end
def locate_label(locator)
XPath.descendant(:label)[XPath.string.n.is(locator)]
end
def find_by_attr(attribute, value)
finder_name = "find_by_#{attribute}_attr"
if respond_to?(finder_name, true)
send(finder_name, value)
else
value ? XPath.attr(attribute) == value : nil
end
end
def find_by_class_attr(classes)
Array(classes).map { |klass| XPath.attr(:class).contains_word(klass) }.reduce(:&)
end
end
end
| ruby | MIT | b3325b198464b806f07ec2011ceb532d6d5cf4ab | 2026-01-04T15:38:10.098638Z | false |
teamcapybara/capybara | https://github.com/teamcapybara/capybara/blob/b3325b198464b806f07ec2011ceb532d6d5cf4ab/lib/capybara/selector/css.rb | lib/capybara/selector/css.rb | # frozen_string_literal: true
require 'capybara/selector/selector'
module Capybara
class Selector
class CSS
def self.escape(str)
value = str.dup
out = +''
out << value.slice!(0...1) if value.match?(/^[-_]/)
out << (value[0].match?(NMSTART) ? value.slice!(0...1) : escape_char(value.slice!(0...1)))
out << value.gsub(/[^a-zA-Z0-9_-]/) { |char| escape_char char }
out
end
def self.escape_char(char)
char.match?(%r{[ -/:-~]}) ? "\\#{char}" : format('\\%06<hex>x', hex: char.ord)
end
def self.split(css)
Splitter.new.split(css)
end
S = '\u{80}-\u{D7FF}\u{E000}-\u{FFFD}\u{10000}-\u{10FFFF}'
H = /[0-9a-fA-F]/
UNICODE = /\\#{H}{1,6}[ \t\r\n\f]?/
NONASCII = /[#{S}]/
ESCAPE = /#{UNICODE}|\\[ -~#{S}]/
NMSTART = /[_a-zA-Z]|#{NONASCII}|#{ESCAPE}/
class Splitter
def split(css)
selectors = []
StringIO.open(css.to_s) do |str|
selector = +''
while (char = str.getc)
case char
when '['
selector << parse_square(str)
when '('
selector << parse_paren(str)
when '"', "'"
selector << parse_string(char, str)
when '\\'
selector << (char + str.getc)
when ','
selectors << selector.strip
selector.clear
else
selector << char
end
end
selectors << selector.strip
end
selectors
end
private
def parse_square(strio)
parse_block('[', ']', strio)
end
def parse_paren(strio)
parse_block('(', ')', strio)
end
def parse_block(start, final, strio)
block = start
while (char = strio.getc)
case char
when final
return block + char
when '\\'
block += char + strio.getc
when '"', "'"
block += parse_string(char, strio)
else
block += char
end
end
raise ArgumentError, "Invalid CSS Selector - Block end '#{final}' not found"
end
def parse_string(quote, strio)
string = quote
while (char = strio.getc)
string += char
case char
when quote
return string
when '\\'
string += strio.getc
end
end
raise ArgumentError, 'Invalid CSS Selector - string end not found'
end
end
end
end
end
| ruby | MIT | b3325b198464b806f07ec2011ceb532d6d5cf4ab | 2026-01-04T15:38:10.098638Z | false |
teamcapybara/capybara | https://github.com/teamcapybara/capybara/blob/b3325b198464b806f07ec2011ceb532d6d5cf4ab/lib/capybara/selector/filter.rb | lib/capybara/selector/filter.rb | # frozen_string_literal: true
require 'capybara/selector/filters/node_filter'
require 'capybara/selector/filters/expression_filter'
require 'capybara/selector/filters/locator_filter'
| ruby | MIT | b3325b198464b806f07ec2011ceb532d6d5cf4ab | 2026-01-04T15:38:10.098638Z | false |
teamcapybara/capybara | https://github.com/teamcapybara/capybara/blob/b3325b198464b806f07ec2011ceb532d6d5cf4ab/lib/capybara/selector/definition.rb | lib/capybara/selector/definition.rb | # frozen_string_literal: true
require 'capybara/selector/filter_set'
require 'capybara/selector/css'
require 'capybara/selector/regexp_disassembler'
require 'capybara/selector/builders/xpath_builder'
require 'capybara/selector/builders/css_builder'
module Capybara
class Selector
class Definition
attr_reader :name, :expressions
extend Forwardable
def initialize(name, locator_type: nil, raw_locator: false, supports_exact: nil, &block)
@name = name
@filter_set = Capybara::Selector::FilterSet.add(name)
@match = nil
@label = nil
@failure_message = nil
@expressions = {}
@expression_filters = {}
@locator_filter = nil
@default_visibility = nil
@locator_type = locator_type
@raw_locator = raw_locator
@supports_exact = supports_exact
instance_eval(&block)
end
def custom_filters
warn "Deprecated: Selector#custom_filters is not valid when same named expression and node filter exist - don't use"
node_filters.merge(expression_filters).freeze
end
def node_filters
@filter_set.node_filters
end
def expression_filters
@filter_set.expression_filters
end
##
#
# Define a selector by an xpath expression
#
# @overload xpath(*expression_filters, &block)
# @param [Array<Symbol>] expression_filters ([]) Names of filters that are implemented via this expression, if not specified the names of any keyword parameters in the block will be used
# @yield [locator, options] The block to use to generate the XPath expression
# @yieldparam [String] locator The locator string passed to the query
# @yieldparam [Hash] options The options hash passed to the query
# @yieldreturn [#to_xpath, #to_s] An object that can produce an xpath expression
#
# @overload xpath()
# @return [#call] The block that will be called to generate the XPath expression
#
def xpath(*allowed_filters, &block)
expression(:xpath, allowed_filters, &block)
end
##
#
# Define a selector by a CSS selector
#
# @overload css(*expression_filters, &block)
# @param [Array<Symbol>] expression_filters ([]) Names of filters that can be implemented via this CSS selector
# @yield [locator, options] The block to use to generate the CSS selector
# @yieldparam [String] locator The locator string passed to the query
# @yieldparam [Hash] options The options hash passed to the query
# @yieldreturn [#to_s] An object that can produce a CSS selector
#
# @overload css()
# @return [#call] The block that will be called to generate the CSS selector
#
def css(*allowed_filters, &block)
expression(:css, allowed_filters, &block)
end
##
#
# Automatic selector detection
#
# @yield [locator] This block takes the passed in locator string and returns whether or not it matches the selector
# @yieldparam [String], locator The locator string used to determine if it matches the selector
# @yieldreturn [Boolean] Whether this selector matches the locator string
# @return [#call] The block that will be used to detect selector match
#
def match(&block)
@match = block if block
@match
end
##
#
# Set/get a descriptive label for the selector
#
# @overload label(label)
# @param [String] label A descriptive label for this selector - used in error messages
# @overload label()
# @return [String] The currently set label
#
def label(label = nil)
@label = label if label
@label
end
##
#
# Description of the selector
#
# @!method description(options)
# @param [Hash] options The options of the query used to generate the description
# @return [String] Description of the selector when used with the options passed
def_delegator :@filter_set, :description
##
#
# Should this selector be used for the passed in locator
#
# This is used by the automatic selector selection mechanism when no selector type is passed to a selector query
#
# @param [String] locator The locator passed to the query
# @return [Boolean] Whether or not to use this selector
#
def match?(locator)
@match&.call(locator)
end
##
#
# Define a node filter for use with this selector
#
# @!method node_filter(name, *types, options={}, &block)
# @param [Symbol, Regexp] name The filter name
# @param [Array<Symbol>] types The types of the filter - currently valid types are [:boolean]
# @param [Hash] options ({}) Options of the filter
# @option options [Array<>] :valid_values Valid values for this filter
# @option options :default The default value of the filter (if any)
# @option options :skip_if Value of the filter that will cause it to be skipped
# @option options [Regexp] :matcher (nil) A Regexp used to check whether a specific option is handled by this filter. If not provided the filter will be used for options matching the filter name.
#
# If a Symbol is passed for the name the block should accept | node, option_value |, while if a Regexp
# is passed for the name the block should accept | node, option_name, option_value |. In either case
# the block should return `true` if the node passes the filer or `false` if it doesn't
##
#
# Define an expression filter for use with this selector
#
# @!method expression_filter(name, *types, matcher: nil, **options, &block)
# @param [Symbol, Regexp] name The filter name
# @param [Regexp] matcher (nil) A Regexp used to check whether a specific option is handled by this filter
# @param [Array<Symbol>] types The types of the filter - currently valid types are [:boolean]
# @param [Hash] options ({}) Options of the filter
# @option options [Array<>] :valid_values Valid values for this filter
# @option options :default The default value of the filter (if any)
# @option options :skip_if Value of the filter that will cause it to be skipped
# @option options [Regexp] :matcher (nil) A Regexp used to check whether a specific option is handled by this filter. If not provided the filter will be used for options matching the filter name.
#
# If a Symbol is passed for the name the block should accept | current_expression, option_value |, while if a Regexp
# is passed for the name the block should accept | current_expression, option_name, option_value |. In either case
# the block should return the modified expression
def_delegators :@filter_set, :node_filter, :expression_filter, :filter
def locator_filter(*types, **options, &block)
types.each { |type| options[type] = true }
@locator_filter = Capybara::Selector::Filters::LocatorFilter.new(block, **options) if block
@locator_filter
end
def filter_set(name, filters_to_use = nil)
@filter_set.import(name, filters_to_use)
end
def_delegator :@filter_set, :describe
def describe_expression_filters(&block)
if block
describe(:expression_filters, &block)
else
describe(:expression_filters) do |**options|
describe_all_expression_filters(**options)
end
end
end
def describe_all_expression_filters(**opts)
expression_filters.map do |ef_name, ef|
if ef.matcher?
handled_custom_options(ef, opts).map { |option, value| " with #{ef_name}[#{option} => #{value}]" }.join
elsif opts.key?(ef_name)
" with #{ef_name} #{opts[ef_name]}"
end
end.join
end
def describe_node_filters(&block)
describe(:node_filters, &block)
end
##
#
# Set the default visibility mode that should be used if no visible option is passed when using the selector.
# If not specified will default to the behavior indicated by Capybara.ignore_hidden_elements
#
# @param [Symbol] default_visibility Only find elements with the specified visibility:
# * :all - finds visible and invisible elements.
# * :hidden - only finds invisible elements.
# * :visible - only finds visible elements.
def visible(default_visibility = nil, &block)
@default_visibility = block || default_visibility
end
def default_visibility(fallback = Capybara.ignore_hidden_elements, options = {})
vis = if @default_visibility.respond_to?(:call)
@default_visibility.call(options)
else
@default_visibility
end
vis.nil? ? fallback : vis
end
# @api private
def raw_locator?
!!@raw_locator
end
# @api private
def supports_exact?
@supports_exact
end
def default_format
return nil if @expressions.keys.empty?
if @expressions.size == 1
@expressions.keys.first
else
:xpath
end
end
# @api private
def locator_types
return nil unless @locator_type
Array(@locator_type)
end
private
def handled_custom_options(filter, options)
options.select do |option, _|
filter.handles_option?(option) && !::Capybara::Queries::SelectorQuery::VALID_KEYS.include?(option)
end
end
def parameter_names(block)
key_types = %i[key keyreq]
# user filter_map when we drop dupport for 2.6
# block.parameters.select { |(type, _name)| key_types.include? type }.map { |(_, name)| name }
block.parameters.filter_map { |(type, name)| name if key_types.include? type }
end
def expression(type, allowed_filters, &block)
if block
@expressions[type] = block
allowed_filters = parameter_names(block) if allowed_filters.empty?
allowed_filters.flatten.each do |ef|
expression_filters[ef] = Capybara::Selector::Filters::IdentityExpressionFilter.new(ef)
end
end
@expressions[type]
end
end
end
end
| ruby | MIT | b3325b198464b806f07ec2011ceb532d6d5cf4ab | 2026-01-04T15:38:10.098638Z | false |
teamcapybara/capybara | https://github.com/teamcapybara/capybara/blob/b3325b198464b806f07ec2011ceb532d6d5cf4ab/lib/capybara/selector/filter_set.rb | lib/capybara/selector/filter_set.rb | # frozen_string_literal: true
require 'capybara/selector/filter'
module Capybara
class Selector
class FilterSet
attr_reader :node_filters, :expression_filters
def initialize(name, &block)
@name = name
@node_filters = {}
@expression_filters = {}
@descriptions = Hash.new { |hsh, key| hsh[key] = [] }
instance_eval(&block) if block
end
def node_filter(names, *types, **options, &block)
Array(names).each do |name|
add_filter(name, Filters::NodeFilter, *types, **options, &block)
end
end
alias_method :filter, :node_filter
def expression_filter(name, *types, **options, &block)
add_filter(name, Filters::ExpressionFilter, *types, **options, &block)
end
def describe(what = nil, &block)
case what
when nil
undeclared_descriptions.push block
when :node_filters
node_filter_descriptions.push block
when :expression_filters
expression_filter_descriptions.push block
else
raise ArgumentError, 'Unknown description type'
end
end
def description(node_filters: true, expression_filters: true, **options)
opts = options_with_defaults(options)
description = +''
description << undeclared_descriptions.map { |desc| desc.call(**opts).to_s }.join
description << expression_filter_descriptions.map { |desc| desc.call(**opts).to_s }.join if expression_filters
description << node_filter_descriptions.map { |desc| desc.call(**opts).to_s }.join if node_filters
description
end
def descriptions
Capybara::Helpers.warn 'DEPRECATED: FilterSet#descriptions is deprecated without replacement'
[undeclared_descriptions, node_filter_descriptions, expression_filter_descriptions].flatten
end
def import(name, filters = nil)
filter_selector = filters.nil? ? ->(*) { true } : ->(filter_name, _) { filters.include? filter_name }
self.class[name].tap do |f_set|
expression_filters.merge!(f_set.expression_filters.select(&filter_selector))
node_filters.merge!(f_set.node_filters.select(&filter_selector))
f_set.undeclared_descriptions.each { |desc| describe(&desc) }
f_set.expression_filter_descriptions.each { |desc| describe(:expression_filters, &desc) }
f_set.node_filter_descriptions.each { |desc| describe(:node_filters, &desc) }
end
self
end
class << self
def all
@filter_sets ||= {} # rubocop:disable Naming/MemoizedInstanceVariableName
end
def [](name)
all.fetch(name.to_sym) { |set_name| raise ArgumentError, "Unknown filter set (:#{set_name})" }
end
def add(name, &block)
all[name.to_sym] = FilterSet.new(name.to_sym, &block)
end
def remove(name)
all.delete(name.to_sym)
end
end
protected
def undeclared_descriptions
@descriptions[:undeclared]
end
def node_filter_descriptions
@descriptions[:node_filters]
end
def expression_filter_descriptions
@descriptions[:expression_filters]
end
private
def options_with_defaults(options)
expression_filters
.chain(node_filters)
.filter_map { |name, filter| [name, filter.default] if filter.default? }
.to_h.merge!(options)
end
def add_filter(name, filter_class, *types, matcher: nil, **options, &block)
types.each { |type| options[type] = true }
if matcher && options[:default]
raise 'ArgumentError', ':default option is not supported for filters with a :matcher option'
end
filter = filter_class.new(name, matcher, block, **options)
(filter_class <= Filters::ExpressionFilter ? @expression_filters : @node_filters)[name] = filter
end
end
end
end
| ruby | MIT | b3325b198464b806f07ec2011ceb532d6d5cf4ab | 2026-01-04T15:38:10.098638Z | false |
teamcapybara/capybara | https://github.com/teamcapybara/capybara/blob/b3325b198464b806f07ec2011ceb532d6d5cf4ab/lib/capybara/selector/xpath_extensions.rb | lib/capybara/selector/xpath_extensions.rb | # frozen_string_literal: true
module XPath
class Renderer
def join(*expressions)
expressions.join('/')
end
end
end
module XPath
module DSL
def join(*expressions)
XPath::Expression.new(:join, *[self, expressions].flatten)
end
end
end
| ruby | MIT | b3325b198464b806f07ec2011ceb532d6d5cf4ab | 2026-01-04T15:38:10.098638Z | false |
teamcapybara/capybara | https://github.com/teamcapybara/capybara/blob/b3325b198464b806f07ec2011ceb532d6d5cf4ab/lib/capybara/selector/regexp_disassembler.rb | lib/capybara/selector/regexp_disassembler.rb | # frozen_string_literal: true
require 'regexp_parser'
module Capybara
class Selector
# @api private
class RegexpDisassembler
def initialize(regexp)
@regexp = regexp
end
def alternated_substrings
@alternated_substrings ||= begin
or_strings = process(alternation: true)
remove_or_covered(or_strings)
or_strings.any?(&:empty?) ? [] : or_strings
end
end
def substrings
@substrings ||= begin
strs = process(alternation: false).first
remove_and_covered(strs)
end
end
private
def remove_and_covered(strings)
# delete_if is documented to modify the array after every block iteration - this doesn't appear to be true
# uniq the strings to prevent identical strings from removing each other
strings.uniq!
# If we have "ab" and "abcd" required - only need to check for "abcd"
strings.delete_if do |sub_string|
strings.any? do |cover_string|
next if sub_string.equal? cover_string
cover_string.include?(sub_string)
end
end
end
def remove_or_covered(or_series)
# If we are going to match `("a" and "b") or ("ade" and "bce")` it only makes sense to match ("a" and "b")
# Ensure minimum sets of strings are being or'd
or_series.each { |strs| remove_and_covered(strs) }
# Remove any of the alternated string series that fully contain any other string series
or_series.delete_if do |and_strs|
or_series.any? do |and_strs2|
next if and_strs.equal? and_strs2
remove_and_covered(and_strs + and_strs2) == and_strs
end
end
end
def process(alternation:)
strs = extract_strings(Regexp::Parser.parse(@regexp), alternation: alternation)
strs = collapse(combine(strs).map(&:flatten))
strs.each { |str| str.map!(&:upcase) } if @regexp.casefold?
strs
end
def combine(strs)
suffixes = [[]]
strs.reverse_each do |str|
if str.is_a? Set
prefixes = str.flat_map { |s| combine(s) }
suffixes = prefixes.product(suffixes).map { |pair| pair.flatten(1) }
else
suffixes.each { |arr| arr.unshift str }
end
end
suffixes
end
def collapse(strs)
strs.map do |substrings|
substrings.slice_before(&:nil?).map(&:join).reject(&:empty?).uniq
end
end
def extract_strings(expression, alternation: false)
Expression.new(expression).extract_strings(alternation)
end
# @api private
class Expression
def initialize(exp)
@exp = exp
end
def extract_strings(process_alternatives)
strings = []
each do |exp|
next if exp.ignore?
next strings.push(nil) if exp.optional? && !process_alternatives
next strings.push(exp.alternative_strings) if exp.alternation? && process_alternatives
strings.concat(exp.strings(process_alternatives))
end
strings
end
protected
def alternation?
(type == :meta) && !terminal?
end
def optional?
min_repeat.zero?
end
def terminal?
@exp.terminal?
end
def strings(process_alternatives)
if indeterminate?
[nil]
elsif terminal?
terminal_strings
elsif optional?
optional_strings
else
repeated_strings(process_alternatives)
end
end
def terminal_strings
text = case @exp.type
when :literal then @exp.text
when :escape then @exp.char
else
return [nil]
end
optional? ? options_set(text) : repeat_set(text)
end
def optional_strings
options_set(extract_strings(true))
end
def repeated_strings(process_alternatives)
repeat_set extract_strings(process_alternatives)
end
def alternative_strings
alts = alternatives.map { |sub_exp| sub_exp.extract_strings(alternation: true) }
alts.all?(&:any?) ? Set.new(alts) : nil
end
def ignore?
[Regexp::Expression::Assertion::NegativeLookahead,
Regexp::Expression::Assertion::NegativeLookbehind].any? { |klass| @exp.is_a? klass }
end
private
def indeterminate?
%i[meta set].include?(type)
end
def min_repeat
@exp.repetitions.begin
end
def max_repeat
@exp.repetitions.end
end
def fixed_repeat?
min_repeat == max_repeat
end
def type
@exp.type
end
def repeat_set(str)
strs = Array(str * min_repeat)
strs.push(nil) unless fixed_repeat?
strs
end
def options_set(strs)
strs = [Set.new([[''], Array(strs)])]
strs.push(nil) unless max_repeat == 1
strs
end
def alternatives
@exp.alternatives.map { |exp| Expression.new(exp) }
end
def each
@exp.each { |exp| yield Expression.new(exp) }
end
end
private_constant :Expression
end
end
end
| ruby | MIT | b3325b198464b806f07ec2011ceb532d6d5cf4ab | 2026-01-04T15:38:10.098638Z | false |
teamcapybara/capybara | https://github.com/teamcapybara/capybara/blob/b3325b198464b806f07ec2011ceb532d6d5cf4ab/lib/capybara/selector/definition/datalist_option.rb | lib/capybara/selector/definition/datalist_option.rb | # frozen_string_literal: true
Capybara.add_selector(:datalist_option, locator_type: [String, Symbol]) do
label 'datalist option'
visible(:all)
xpath do |locator|
xpath = XPath.descendant(:option)
xpath = xpath[XPath.string.n.is(locator.to_s) | (XPath.attr(:value) == locator.to_s)] unless locator.nil?
xpath
end
node_filter(:disabled, :boolean) { |node, value| !(value ^ node.disabled?) }
expression_filter(:disabled) { |xpath, val| val ? xpath : xpath[~XPath.attr(:disabled)] }
describe_expression_filters do |disabled: nil, **options|
desc = +''
desc << ' that is not disabled' if disabled == false
desc << describe_all_expression_filters(**options)
end
describe_node_filters do |**options|
' that is disabled' if options[:disabled]
end
end
| ruby | MIT | b3325b198464b806f07ec2011ceb532d6d5cf4ab | 2026-01-04T15:38:10.098638Z | false |
teamcapybara/capybara | https://github.com/teamcapybara/capybara/blob/b3325b198464b806f07ec2011ceb532d6d5cf4ab/lib/capybara/selector/definition/link_or_button.rb | lib/capybara/selector/definition/link_or_button.rb | # frozen_string_literal: true
Capybara.add_selector(:link_or_button, locator_type: [String, Symbol]) do
label 'link or button'
xpath do |locator, **options|
%i[link button].map do |selector|
expression_for(selector, locator, **options)
end.reduce(:union)
end
node_filter(:disabled, :boolean, default: false, skip_if: :all) { |node, value| !(value ^ node.disabled?) }
describe_node_filters do |disabled: nil, **|
' that is disabled' if disabled == true
end
end
| ruby | MIT | b3325b198464b806f07ec2011ceb532d6d5cf4ab | 2026-01-04T15:38:10.098638Z | false |
teamcapybara/capybara | https://github.com/teamcapybara/capybara/blob/b3325b198464b806f07ec2011ceb532d6d5cf4ab/lib/capybara/selector/definition/element.rb | lib/capybara/selector/definition/element.rb | # frozen_string_literal: true
Capybara.add_selector(:element, locator_type: [String, Symbol]) do
xpath do |locator, **|
XPath.descendant.where(locator ? XPath.local_name == locator.to_s : nil)
end
expression_filter(:attributes, matcher: /.+/) do |xpath, name, val|
builder(xpath).add_attribute_conditions(name => val)
end
node_filter(:attributes, matcher: /.+/) do |node, name, val|
next true unless val.is_a?(Regexp)
(val.match? node[name]).tap do |res|
add_error("Expected #{name} to match #{val.inspect} but it was #{node[name]}") unless res
end
end
describe_expression_filters do |**options|
boolean_values = [true, false]
booleans, values = options.partition { |_k, v| boolean_values.include? v }.map(&:to_h)
desc = describe_all_expression_filters(**values)
desc + booleans.map do |k, v|
v ? " with #{k} attribute" : "without #{k} attribute"
end.join
end
end
| ruby | MIT | b3325b198464b806f07ec2011ceb532d6d5cf4ab | 2026-01-04T15:38:10.098638Z | false |
teamcapybara/capybara | https://github.com/teamcapybara/capybara/blob/b3325b198464b806f07ec2011ceb532d6d5cf4ab/lib/capybara/selector/definition/table.rb | lib/capybara/selector/definition/table.rb | # frozen_string_literal: true
Capybara.add_selector(:table, locator_type: [String, Symbol]) do
xpath do |locator, caption: nil, **|
xpath = XPath.descendant(:table)
unless locator.nil?
locator_matchers = (XPath.attr(:id) == locator.to_s) | XPath.descendant(:caption).is(locator.to_s)
locator_matchers |= XPath.attr(test_id) == locator.to_s if test_id
xpath = xpath[locator_matchers]
end
xpath = xpath[XPath.descendant(:caption) == caption] if caption
xpath
end
expression_filter(:with_cols, valid_values: [Array]) do |xpath, cols|
col_conditions = cols.map do |col|
if col.is_a? Hash
col.reduce(nil) do |xp, (header, cell_str)|
header = XPath.descendant(:th)[XPath.string.n.is(header)]
td = XPath.descendant(:tr)[header].descendant(:td)
cell_condition = XPath.string.n.is(cell_str)
if xp
prev_cell = XPath.ancestor(:table)[1].join(xp)
cell_condition &= (prev_cell & prev_col_position?(prev_cell))
end
td[cell_condition]
end
else
cells_xp = col.reduce(nil) do |prev_cell, cell_str|
cell_condition = XPath.string.n.is(cell_str)
if prev_cell
prev_cell = XPath.ancestor(:tr)[1].preceding_sibling(:tr).join(prev_cell)
cell_condition &= (prev_cell & prev_col_position?(prev_cell))
end
XPath.descendant(:td)[cell_condition]
end
XPath.descendant(:tr).join(cells_xp)
end
end.reduce(:&)
xpath[col_conditions]
end
expression_filter(:cols, valid_values: [Array]) do |xpath, cols|
raise ArgumentError, ':cols must be an Array of Arrays' unless cols.all?(Array)
rows = cols.transpose
col_conditions = rows.map { |row| match_row(row, match_size: true) }.reduce(:&)
xpath[match_row_count(rows.size)][col_conditions]
end
expression_filter(:with_rows, valid_values: [Array]) do |xpath, rows|
rows_conditions = rows.map { |row| match_row(row) }.reduce(:&)
xpath[rows_conditions]
end
expression_filter(:rows, valid_values: [Array]) do |xpath, rows|
rows_conditions = rows.map { |row| match_row(row, match_size: true) }.reduce(:&)
xpath[match_row_count(rows.size)][rows_conditions]
end
describe_expression_filters do |caption: nil, **|
" with caption \"#{caption}\"" if caption
end
def prev_col_position?(cell)
XPath.position.equals(cell_position(cell))
end
def cell_position(cell)
cell.preceding_sibling(:td).count.plus(1)
end
def match_row(row, match_size: false)
xp = XPath.descendant(:tr)[
if row.is_a? Hash
row_match_cells_to_headers(row)
else
XPath.descendant(:td)[row_match_ordered_cells(row)]
end
]
xp = xp[XPath.descendant(:td).count.equals(row.size)] if match_size
xp
end
def match_row_count(size)
XPath.descendant(:tbody).descendant(:tr).count.equals(size) |
(XPath.descendant(:tr).count.equals(size) & ~XPath.descendant(:tbody))
end
def row_match_cells_to_headers(row)
row.map do |header, cell|
header_xp = XPath.ancestor(:table)[1].descendant(:tr)[1].descendant(:th)[XPath.string.n.is(header)]
XPath.descendant(:td)[
XPath.string.n.is(cell) & header_xp.boolean & XPath.position.equals(header_xp.preceding_sibling.count.plus(1))
]
end.reduce(:&)
end
def row_match_ordered_cells(row)
row_conditions = row.map do |cell|
XPath.self(:td)[XPath.string.n.is(cell)]
end
row_conditions.reverse.reduce do |cond, cell|
cell[XPath.following_sibling[cond]]
end
end
end
| ruby | MIT | b3325b198464b806f07ec2011ceb532d6d5cf4ab | 2026-01-04T15:38:10.098638Z | false |
teamcapybara/capybara | https://github.com/teamcapybara/capybara/blob/b3325b198464b806f07ec2011ceb532d6d5cf4ab/lib/capybara/selector/definition/xpath.rb | lib/capybara/selector/definition/xpath.rb | # frozen_string_literal: true
Capybara.add_selector(:xpath, locator_type: [:to_xpath, String], raw_locator: true) do
xpath { |xpath| xpath }
end
| ruby | MIT | b3325b198464b806f07ec2011ceb532d6d5cf4ab | 2026-01-04T15:38:10.098638Z | false |
teamcapybara/capybara | https://github.com/teamcapybara/capybara/blob/b3325b198464b806f07ec2011ceb532d6d5cf4ab/lib/capybara/selector/definition/fieldset.rb | lib/capybara/selector/definition/fieldset.rb | # frozen_string_literal: true
Capybara.add_selector(:fieldset, locator_type: [String, Symbol]) do
xpath do |locator, legend: nil, **|
locator_matchers = (XPath.attr(:id) == locator.to_s) | XPath.child(:legend)[XPath.string.n.is(locator.to_s)]
locator_matchers |= XPath.attr(test_id) == locator.to_s if test_id
xpath = XPath.descendant(:fieldset)[locator && locator_matchers]
xpath = xpath[XPath.child(:legend)[XPath.string.n.is(legend)]] if legend
xpath
end
node_filter(:disabled, :boolean) { |node, value| !(value ^ node.disabled?) }
expression_filter(:disabled) { |xpath, val| val ? xpath : xpath[~XPath.attr(:disabled)] }
end
| ruby | MIT | b3325b198464b806f07ec2011ceb532d6d5cf4ab | 2026-01-04T15:38:10.098638Z | false |
teamcapybara/capybara | https://github.com/teamcapybara/capybara/blob/b3325b198464b806f07ec2011ceb532d6d5cf4ab/lib/capybara/selector/definition/css.rb | lib/capybara/selector/definition/css.rb | # frozen_string_literal: true
Capybara.add_selector(:css, locator_type: [String, Symbol], raw_locator: true) do
css do |css|
if css.is_a? Symbol
Capybara::Helpers.warn "DEPRECATED: Passing a symbol (#{css.inspect}) as the CSS locator is deprecated - please pass a string instead : #{Capybara::Helpers.filter_backtrace(caller)}"
end
css
end
end
| ruby | MIT | b3325b198464b806f07ec2011ceb532d6d5cf4ab | 2026-01-04T15:38:10.098638Z | false |
teamcapybara/capybara | https://github.com/teamcapybara/capybara/blob/b3325b198464b806f07ec2011ceb532d6d5cf4ab/lib/capybara/selector/definition/id.rb | lib/capybara/selector/definition/id.rb | # frozen_string_literal: true
Capybara.add_selector(:id, locator_type: [String, Symbol, Regexp]) do
xpath { |id| builder(XPath.descendant).add_attribute_conditions(id: id) }
locator_filter { |node, id| id.is_a?(Regexp) ? id.match?(node[:id]) : true }
end
| ruby | MIT | b3325b198464b806f07ec2011ceb532d6d5cf4ab | 2026-01-04T15:38:10.098638Z | false |
teamcapybara/capybara | https://github.com/teamcapybara/capybara/blob/b3325b198464b806f07ec2011ceb532d6d5cf4ab/lib/capybara/selector/definition/select.rb | lib/capybara/selector/definition/select.rb | # frozen_string_literal: true
Capybara.add_selector(:select, locator_type: [String, Symbol]) do
label 'select box'
xpath do |locator, **options|
xpath = XPath.descendant(:select)
locate_field(xpath, locator, **options)
end
filter_set(:_field, %i[disabled multiple name placeholder])
node_filter(:options) do |node, options|
actual = options_text(node)
(options.sort == actual.sort).tap do |res|
add_error("Expected options #{options.inspect} found #{actual.inspect}") unless res
end
end
node_filter(:enabled_options) do |node, options|
actual = options_text(node) { |o| !o.disabled? }
(options.sort == actual.sort).tap do |res|
add_error("Expected enabled options #{options.inspect} found #{actual.inspect}") unless res
end
end
node_filter(:disabled_options) do |node, options|
actual = options_text(node, &:disabled?)
(options.sort == actual.sort).tap do |res|
add_error("Expected disabled options #{options.inspect} found #{actual.inspect}") unless res
end
end
expression_filter(:with_options) do |expr, options|
options.inject(expr) do |xpath, option|
xpath.where(expression_for(:option, option))
end
end
node_filter(:selected) do |node, selected|
actual = options_text(node, visible: false, &:selected?)
(Array(selected).sort == actual.sort).tap do |res|
add_error("Expected #{selected.inspect} to be selected found #{actual.inspect}") unless res
end
end
node_filter(:with_selected) do |node, selected|
actual = options_text(node, visible: false, &:selected?)
(Array(selected) - actual).empty?.tap do |res|
add_error("Expected at least #{selected.inspect} to be selected found #{actual.inspect}") unless res
end
end
describe_expression_filters do |with_options: nil, **|
desc = +''
desc << " with at least options #{with_options.inspect}" if with_options
desc
end
describe_node_filters do |
options: nil, disabled_options: nil, enabled_options: nil,
selected: nil, with_selected: nil,
disabled: nil, **|
desc = +''
desc << " with options #{options.inspect}" if options
desc << " with disabled options #{disabled_options.inspect}}" if disabled_options
desc << " with enabled options #{enabled_options.inspect}" if enabled_options
desc << " with #{selected.inspect} selected" if selected
desc << " with at least #{with_selected.inspect} selected" if with_selected
desc << ' which is disabled' if disabled
desc
end
def options_text(node, **opts, &filter_block)
opts[:wait] = false
opts[:visible] = false unless node.visible?
node.all(:xpath, './/option', **opts, &filter_block).map do |o|
o.text((:all if opts[:visible] == false))
end
end
end
| ruby | MIT | b3325b198464b806f07ec2011ceb532d6d5cf4ab | 2026-01-04T15:38:10.098638Z | false |
teamcapybara/capybara | https://github.com/teamcapybara/capybara/blob/b3325b198464b806f07ec2011ceb532d6d5cf4ab/lib/capybara/selector/definition/frame.rb | lib/capybara/selector/definition/frame.rb | # frozen_string_literal: true
Capybara.add_selector(:frame, locator_type: [String, Symbol]) do
xpath do |locator, name: nil, **|
xpath = XPath.descendant(:iframe).union(XPath.descendant(:frame))
unless locator.nil?
locator_matchers = (XPath.attr(:id) == locator.to_s) | (XPath.attr(:name) == locator.to_s)
locator_matchers |= XPath.attr(test_id) == locator.to_s if test_id
xpath = xpath[locator_matchers]
end
xpath[find_by_attr(:name, name)]
end
describe_expression_filters do |name: nil, **|
" with name #{name}" if name
end
end
| ruby | MIT | b3325b198464b806f07ec2011ceb532d6d5cf4ab | 2026-01-04T15:38:10.098638Z | false |
teamcapybara/capybara | https://github.com/teamcapybara/capybara/blob/b3325b198464b806f07ec2011ceb532d6d5cf4ab/lib/capybara/selector/definition/field.rb | lib/capybara/selector/definition/field.rb | # frozen_string_literal: true
Capybara.add_selector(:field, locator_type: [String, Symbol]) do
visible { |options| :hidden if options[:type].to_s == 'hidden' }
xpath do |locator, **options|
invalid_types = %w[submit image]
invalid_types << 'hidden' unless options[:type].to_s == 'hidden'
xpath = XPath.descendant(:input, :textarea, :select)[!XPath.attr(:type).one_of(*invalid_types)]
locate_field(xpath, locator, **options)
end
expression_filter(:type) do |expr, type|
type = type.to_s
if %w[textarea select].include?(type)
expr.self(type.to_sym)
else
expr[XPath.attr(:type) == type]
end
end
filter_set(:_field) # checked/unchecked/disabled/multiple/name/placeholder
node_filter(:readonly, :boolean) { |node, value| !(value ^ node.readonly?) }
node_filter(:with) do |node, with|
val = node.value
(with.is_a?(Regexp) ? with.match?(val) : val == with.to_s).tap do |res|
add_error("Expected value to be #{with.inspect} but was #{val.inspect}") unless res
end
end
describe_expression_filters do |type: nil, **|
" of type #{type.inspect}" if type
end
describe_node_filters do |**options|
" with value #{options[:with].to_s.inspect}" if options.key?(:with)
end
end
| ruby | MIT | b3325b198464b806f07ec2011ceb532d6d5cf4ab | 2026-01-04T15:38:10.098638Z | false |
teamcapybara/capybara | https://github.com/teamcapybara/capybara/blob/b3325b198464b806f07ec2011ceb532d6d5cf4ab/lib/capybara/selector/definition/radio_button.rb | lib/capybara/selector/definition/radio_button.rb | # frozen_string_literal: true
Capybara.add_selector(:radio_button, locator_type: [String, Symbol]) do
label 'radio button'
xpath do |locator, allow_self: nil, **options|
xpath = XPath.axis(allow_self ? :'descendant-or-self' : :descendant, :input)[
XPath.attr(:type) == 'radio'
]
locate_field(xpath, locator, **options)
end
filter_set(:_field, %i[checked unchecked disabled name])
node_filter(%i[option with]) do |node, value|
val = node.value
(value.is_a?(Regexp) ? value.match?(val) : val == value.to_s).tap do |res|
add_error("Expected value to be #{value.inspect} but it was #{val.inspect}") unless res
end
end
describe_node_filters do |option: nil, with: nil, **|
desc = +''
desc << " with value #{option.inspect}" if option
desc << " with value #{with.inspect}" if with
desc
end
end
| ruby | MIT | b3325b198464b806f07ec2011ceb532d6d5cf4ab | 2026-01-04T15:38:10.098638Z | false |
teamcapybara/capybara | https://github.com/teamcapybara/capybara/blob/b3325b198464b806f07ec2011ceb532d6d5cf4ab/lib/capybara/selector/definition/button.rb | lib/capybara/selector/definition/button.rb | # frozen_string_literal: true
Capybara.add_selector(:button, locator_type: [String, Symbol]) do
xpath(:value, :title, :type, :name) do |locator, **options|
input_btn_xpath = XPath.descendant(:input)[XPath.attr(:type).one_of('submit', 'reset', 'image', 'button')]
btn_xpath = XPath.descendant(:button)
aria_btn_xpath = XPath.descendant[XPath.attr(:role).equals('button')]
image_btn_xpath = XPath.descendant(:input)[XPath.attr(:type) == 'image']
unless locator.nil?
locator = locator.to_s
locator_matchers = combine_locators(locator, config: self)
btn_matchers = locator_matchers |
XPath.string.n.is(locator) |
XPath.descendant(:img)[XPath.attr(:alt).is(locator)]
label_contains_xpath = locate_label(locator).descendant[labellable_elements]
input_btn_xpath = input_btn_xpath[locator_matchers]
btn_xpath = btn_xpath[btn_matchers]
aria_btn_xpath = aria_btn_xpath[btn_matchers]
alt_matches = XPath.attr(:alt).is(locator)
alt_matches |= XPath.attr(:'aria-label').is(locator) if enable_aria_label
image_btn_xpath = image_btn_xpath[alt_matches]
end
btn_xpaths = [input_btn_xpath, btn_xpath, image_btn_xpath, label_contains_xpath].compact
btn_xpaths << aria_btn_xpath if enable_aria_role
%i[value title type].inject(btn_xpaths.inject(&:union)) do |memo, ef|
memo.where(find_by_attr(ef, options[ef]))
end
end
node_filter(:disabled, :boolean, default: false, skip_if: :all) { |node, value| !(value ^ node.disabled?) }
expression_filter(:disabled) { |xpath, val| val ? xpath : xpath[~XPath.attr(:disabled)] }
node_filter(:name) { |node, value| !value.is_a?(Regexp) || value.match?(node[:name]) }
expression_filter(:name) do |xpath, val|
builder(xpath).add_attribute_conditions(name: val)
end
describe_expression_filters do |disabled: nil, **options|
desc = +''
desc << ' that is not disabled' if disabled == false
desc << describe_all_expression_filters(**options)
end
describe_node_filters do |disabled: nil, **|
' that is disabled' if disabled == true
end
def combine_locators(locator, config:)
[
XPath.attr(:id).equals(locator),
XPath.attr(:name).equals(locator),
XPath.attr(:value).is(locator),
XPath.attr(:title).is(locator),
(XPath.attr(:id) == XPath.anywhere(:label)[XPath.string.n.is(locator)].attr(:for)),
(XPath.attr(:'aria-label').is(locator) if config.enable_aria_label),
(XPath.attr(config.test_id) == locator if config.test_id)
].compact.inject(&:|)
end
def labellable_elements
(XPath.self(:input) & XPath.attr(:type).one_of('submit', 'reset', 'image', 'button')) | XPath.self(:button)
end
end
| ruby | MIT | b3325b198464b806f07ec2011ceb532d6d5cf4ab | 2026-01-04T15:38:10.098638Z | false |
teamcapybara/capybara | https://github.com/teamcapybara/capybara/blob/b3325b198464b806f07ec2011ceb532d6d5cf4ab/lib/capybara/selector/definition/link.rb | lib/capybara/selector/definition/link.rb | # frozen_string_literal: true
Capybara.add_selector(:link, locator_type: [String, Symbol]) do
xpath do |locator, href: true, alt: nil, title: nil, target: nil, **|
xpath = XPath.descendant(:a)
xpath = builder(xpath).add_attribute_conditions(href: href) unless href == false
if enable_aria_role
role_path = XPath.descendant[XPath.attr(:role).equals('link')]
role_path = builder(role_path).add_attribute_conditions(href: href) unless [true, false].include? href
xpath += role_path
end
unless locator.nil?
locator = locator.to_s
matchers = [XPath.attr(:id) == locator,
XPath.string.n.is(locator),
XPath.attr(:title).is(locator),
XPath.descendant(:img)[XPath.attr(:alt).is(locator)]]
matchers << XPath.attr(:'aria-label').is(locator) if enable_aria_label
matchers << XPath.attr(test_id).equals(locator) if test_id
xpath = xpath[matchers.reduce(:|)]
end
xpath = xpath[find_by_attr(:title, title)]
xpath = xpath[XPath.descendant(:img)[XPath.attr(:alt) == alt]] if alt
xpath = xpath[find_by_attr(:target, target)] if target
xpath
end
node_filter(:href) do |node, href|
# If not a Regexp it's been handled in the main XPath
(href.is_a?(Regexp) ? node[:href].match?(href) : true).tap do |res|
add_error "Expected href to match #{href.inspect} but it was #{node[:href].inspect}" unless res
end
end
expression_filter(:download, valid_values: [true, false, String]) do |expr, download|
builder(expr).add_attribute_conditions(download: download)
end
describe_expression_filters do |download: nil, **options|
desc = +''
if (href = options[:href])
desc << " with href #{'matching ' if href.is_a? Regexp}#{href.inspect}"
elsif options.key?(:href) && href != false # is nil specified?
desc << ' with no href attribute'
end
desc << " with download attribute#{" #{download}" if download.is_a? String}" if download
desc << ' without download attribute' if download == false
desc
end
end
| ruby | MIT | b3325b198464b806f07ec2011ceb532d6d5cf4ab | 2026-01-04T15:38:10.098638Z | false |
teamcapybara/capybara | https://github.com/teamcapybara/capybara/blob/b3325b198464b806f07ec2011ceb532d6d5cf4ab/lib/capybara/selector/definition/datalist_input.rb | lib/capybara/selector/definition/datalist_input.rb | # frozen_string_literal: true
Capybara.add_selector(:datalist_input, locator_type: [String, Symbol]) do
label 'input box with datalist completion'
xpath do |locator, **options|
xpath = XPath.descendant(:input)[XPath.attr(:list)]
locate_field(xpath, locator, **options)
end
filter_set(:_field, %i[disabled name placeholder])
node_filter(:options) do |node, options|
actual = node.find("//datalist[@id=#{node[:list]}]", visible: :all).all(:datalist_option, wait: false).map(&:value)
(options.sort == actual.sort).tap do |res|
add_error("Expected #{options.inspect} options found #{actual.inspect}") unless res
end
end
expression_filter(:with_options) do |expr, options|
options.inject(expr) do |xpath, option|
xpath.where(XPath.attr(:list) == XPath.anywhere(:datalist)[expression_for(:datalist_option, option)].attr(:id))
end
end
describe_expression_filters do |with_options: nil, **|
desc = +''
desc << " with at least options #{with_options.inspect}" if with_options
desc
end
describe_node_filters do |options: nil, **|
" with options #{options.inspect}" if options
end
end
| ruby | MIT | b3325b198464b806f07ec2011ceb532d6d5cf4ab | 2026-01-04T15:38:10.098638Z | false |
teamcapybara/capybara | https://github.com/teamcapybara/capybara/blob/b3325b198464b806f07ec2011ceb532d6d5cf4ab/lib/capybara/selector/definition/table_row.rb | lib/capybara/selector/definition/table_row.rb | # frozen_string_literal: true
Capybara.add_selector(:table_row, locator_type: [Array, Hash]) do
xpath do |locator|
xpath = XPath.descendant(:tr)
if locator.is_a? Hash
locator.reduce(xpath) do |xp, (header, cell)|
header_xp = XPath.ancestor(:table)[1].descendant(:tr)[1].descendant(:th)[XPath.string.n.is(header)]
cell_xp = XPath.descendant(:td)[
XPath.string.n.is(cell) & header_xp.boolean & XPath.position.equals(header_xp.preceding_sibling.count.plus(1))
]
xp.where(cell_xp)
end
elsif locator.is_a? Array
initial_td = XPath.descendant(:td)[XPath.string.n.is(locator.shift)]
tds = locator.reverse.map { |cell| XPath.following_sibling(:td)[XPath.string.n.is(cell)] }
.reduce { |xp, cell| cell.where(xp) }
xpath[initial_td[tds]]
else
xpath
end
end
end
| ruby | MIT | b3325b198464b806f07ec2011ceb532d6d5cf4ab | 2026-01-04T15:38:10.098638Z | false |
teamcapybara/capybara | https://github.com/teamcapybara/capybara/blob/b3325b198464b806f07ec2011ceb532d6d5cf4ab/lib/capybara/selector/definition/fillable_field.rb | lib/capybara/selector/definition/fillable_field.rb | # frozen_string_literal: true
Capybara.add_selector(:fillable_field, locator_type: [String, Symbol]) do
label 'field'
xpath do |locator, allow_self: nil, **options|
xpath = XPath.axis(allow_self ? :'descendant-or-self' : :descendant, :input, :textarea)[
!XPath.attr(:type).one_of('submit', 'image', 'radio', 'checkbox', 'hidden', 'file')
]
locate_field(xpath, locator, **options)
end
expression_filter(:type) do |expr, type|
type = type.to_s
if type == 'textarea'
expr.self(type.to_sym)
else
expr[XPath.attr(:type) == type]
end
end
filter_set(:_field, %i[disabled multiple name placeholder valid validation_message])
node_filter(:with) do |node, with|
val = node.value
(with.is_a?(Regexp) ? with.match?(val) : val == with.to_s).tap do |res|
add_error("Expected value to be #{with.inspect} but was #{val.inspect}") unless res
end
end
describe_node_filters do |**options|
" with value #{options[:with].to_s.inspect}" if options.key?(:with)
end
end
| ruby | MIT | b3325b198464b806f07ec2011ceb532d6d5cf4ab | 2026-01-04T15:38:10.098638Z | false |
teamcapybara/capybara | https://github.com/teamcapybara/capybara/blob/b3325b198464b806f07ec2011ceb532d6d5cf4ab/lib/capybara/selector/definition/option.rb | lib/capybara/selector/definition/option.rb | # frozen_string_literal: true
Capybara.add_selector(:option, locator_type: [String, Symbol, Integer]) do
xpath do |locator|
xpath = XPath.descendant(:option)
xpath = xpath[XPath.string.n.is(locator.to_s)] unless locator.nil?
xpath
end
node_filter(:disabled, :boolean) { |node, value| !(value ^ node.disabled?) }
expression_filter(:disabled) { |xpath, val| val ? xpath : xpath[~XPath.attr(:disabled)] }
node_filter(:selected, :boolean) { |node, value| !(value ^ node.selected?) }
describe_expression_filters do |disabled: nil, **options|
desc = +''
desc << ' that is not disabled' if disabled == false
(expression_filters.keys & options.keys).inject(desc) { |memo, ef| memo << " with #{ef} #{options[ef]}" }
end
describe_node_filters do |**options|
desc = +''
desc << ' that is disabled' if options[:disabled]
desc << " that is#{' not' unless options[:selected]} selected" if options.key?(:selected)
desc
end
end
| ruby | MIT | b3325b198464b806f07ec2011ceb532d6d5cf4ab | 2026-01-04T15:38:10.098638Z | false |
teamcapybara/capybara | https://github.com/teamcapybara/capybara/blob/b3325b198464b806f07ec2011ceb532d6d5cf4ab/lib/capybara/selector/definition/file_field.rb | lib/capybara/selector/definition/file_field.rb | # frozen_string_literal: true
Capybara.add_selector(:file_field, locator_type: [String, Symbol]) do
label 'file field'
xpath do |locator, allow_self: nil, **options|
xpath = XPath.axis(allow_self ? :'descendant-or-self' : :descendant, :input)[
XPath.attr(:type) == 'file'
]
locate_field(xpath, locator, **options)
end
filter_set(:_field, %i[disabled multiple name])
end
| ruby | MIT | b3325b198464b806f07ec2011ceb532d6d5cf4ab | 2026-01-04T15:38:10.098638Z | false |
teamcapybara/capybara | https://github.com/teamcapybara/capybara/blob/b3325b198464b806f07ec2011ceb532d6d5cf4ab/lib/capybara/selector/definition/checkbox.rb | lib/capybara/selector/definition/checkbox.rb | # frozen_string_literal: true
Capybara.add_selector(:checkbox, locator_type: [String, Symbol]) do
xpath do |locator, allow_self: nil, **options|
xpath = XPath.axis(allow_self ? :'descendant-or-self' : :descendant, :input)[
XPath.attr(:type) == 'checkbox'
]
locate_field(xpath, locator, **options)
end
filter_set(:_field, %i[checked unchecked disabled name])
node_filter(%i[option with]) do |node, value|
val = node.value
(value.is_a?(Regexp) ? value.match?(val) : val == value.to_s).tap do |res|
add_error("Expected value to be #{value.inspect} but it was #{val.inspect}") unless res
end
end
describe_node_filters do |option: nil, with: nil, **|
desc = +''
desc << " with value #{option.inspect}" if option
desc << " with value #{with.inspect}" if with
desc
end
end
| ruby | MIT | b3325b198464b806f07ec2011ceb532d6d5cf4ab | 2026-01-04T15:38:10.098638Z | false |
teamcapybara/capybara | https://github.com/teamcapybara/capybara/blob/b3325b198464b806f07ec2011ceb532d6d5cf4ab/lib/capybara/selector/definition/label.rb | lib/capybara/selector/definition/label.rb | # frozen_string_literal: true
Capybara.add_selector(:label, locator_type: [String, Symbol]) do
label 'label'
xpath(:for) do |locator, **options|
xpath = XPath.descendant(:label)
unless locator.nil?
locator_matchers = XPath.string.n.is(locator.to_s) | (XPath.attr(:id) == locator.to_s)
locator_matchers |= XPath.attr(test_id) == locator.to_s if test_id
xpath = xpath[locator_matchers]
end
if options.key?(:for)
for_option = options[:for]
for_option = for_option[:id] if for_option.is_a?(Capybara::Node::Element)
if for_option && (for_option != '')
with_attr = builder(XPath.self).add_attribute_conditions(for: for_option)
wrapped = !XPath.attr(:for) &
builder(XPath.self.descendant(*labelable_elements)).add_attribute_conditions(id: for_option)
xpath = xpath[with_attr | wrapped]
end
end
xpath
end
node_filter(:for) do |node, field_or_value|
case field_or_value
when Capybara::Node::Element
if (for_val = node[:for])
field_or_value[:id] == for_val
else
field_or_value.find_xpath('./ancestor::label[1]').include? node.base
end
when Regexp
if (for_val = node[:for])
field_or_value.match? for_val
else
node.find_xpath(XPath.descendant(*labelable_elements).to_s)
.any? { |n| field_or_value.match? n[:id] }
end
else
# Non element/regexp values were handled through the expression filter
true
end
end
describe_expression_filters do |**options|
next unless options.key?(:for) && !options[:for].is_a?(Capybara::Node::Element)
if options[:for].is_a? Regexp
" for element with id matching #{options[:for].inspect}"
else
" for element with id of \"#{options[:for]}\""
end
end
describe_node_filters do |**options|
" for element #{options[:for]}" if options[:for].is_a?(Capybara::Node::Element)
end
def labelable_elements
%i[button input keygen meter output progress select textarea]
end
end
| ruby | MIT | b3325b198464b806f07ec2011ceb532d6d5cf4ab | 2026-01-04T15:38:10.098638Z | false |
teamcapybara/capybara | https://github.com/teamcapybara/capybara/blob/b3325b198464b806f07ec2011ceb532d6d5cf4ab/lib/capybara/selector/filters/expression_filter.rb | lib/capybara/selector/filters/expression_filter.rb | # frozen_string_literal: true
require 'capybara/selector/filters/base'
module Capybara
class Selector
module Filters
class ExpressionFilter < Base
def apply_filter(expr, name, value, selector)
apply(expr, name, value, expr, selector)
end
end
class IdentityExpressionFilter < ExpressionFilter
def initialize(name); super(name, nil, nil); end
def default?; false; end
def matcher?; false; end
def apply_filter(expr, _name, _value, _ctx); expr; end
end
end
end
end
| ruby | MIT | b3325b198464b806f07ec2011ceb532d6d5cf4ab | 2026-01-04T15:38:10.098638Z | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.