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/lib/capybara/selector/filters/node_filter.rb | lib/capybara/selector/filters/node_filter.rb | # frozen_string_literal: true
require 'capybara/selector/filters/base'
module Capybara
class Selector
module Filters
class NodeFilter < Base
def initialize(name, matcher, block, **options)
super
@block = if boolean?
proc do |node, value|
error_cnt = errors.size
block.call(node, value).tap do |res|
add_error("Expected #{name} #{value} but it wasn't") if !res && error_cnt == errors.size
end
end
else
block
end
end
def matches?(node, name, value, context = nil)
apply(node, name, value, true, context)
rescue Capybara::ElementNotFound
false
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/filters/base.rb | lib/capybara/selector/filters/base.rb | # frozen_string_literal: true
module Capybara
class Selector
module Filters
class Base
def initialize(name, matcher, block, **options)
@name = name
@matcher = matcher
@block = block
@options = options
@options[:valid_values] = [true, false] if options[:boolean]
end
def default?
@options.key?(:default)
end
def default
@options[:default]
end
def skip?(value)
@options.key?(:skip_if) && value == @options[:skip_if]
end
def format
@options[:format]
end
def matcher?
!@matcher.nil?
end
def boolean?
!!@options[:boolean]
end
def handles_option?(option_name)
if matcher?
@matcher.match? option_name
else
@name == option_name
end
end
private
def apply(subject, name, value, skip_value, ctx)
return skip_value if skip?(value)
unless valid_value?(value)
raise ArgumentError,
"Invalid value #{value.inspect} passed to #{self.class.name.split('::').last} #{name}" \
"#{" : #{name}" if @name.is_a?(Regexp)}"
end
if @block.arity == 2
filter_context(ctx).instance_exec(subject, value, &@block)
else
filter_context(ctx).instance_exec(subject, name, value, &@block)
end
end
def filter_context(context)
context || @block.binding.receiver
end
def valid_value?(value)
return true unless @options.key?(:valid_values)
Array(@options[:valid_values]).any? { |valid| valid === value } # rubocop:disable Style/CaseEquality
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/filters/locator_filter.rb | lib/capybara/selector/filters/locator_filter.rb | # frozen_string_literal: true
require 'capybara/selector/filters/base'
module Capybara
class Selector
module Filters
class LocatorFilter < NodeFilter
def initialize(block, **options)
super(nil, nil, block, **options)
end
def matches?(node, value, context = nil, exact:)
apply(node, value, true, context, exact: exact, format: context&.default_format)
rescue Capybara::ElementNotFound
false
end
private
def apply(subject, value, skip_value, ctx, **options)
return skip_value if skip?(value)
filter_context(ctx).instance_exec(subject, value, **options, &@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/selector/builders/xpath_builder.rb | lib/capybara/selector/builders/xpath_builder.rb | # frozen_string_literal: true
require 'xpath'
module Capybara
class Selector
# @api private
class XPathBuilder
def initialize(expression)
@expression = expression || ''
end
attr_reader :expression
def add_attribute_conditions(**conditions)
@expression = conditions.inject(expression) do |xp, (name, value)|
conditions = name == :class ? class_conditions(value) : attribute_conditions(name => value)
return xp if conditions.nil?
if xp.is_a? XPath::Expression
xp[conditions]
else
"(#{xp})[#{conditions}]"
end
end
end
private
def attribute_conditions(attributes)
attributes.map do |attribute, value|
case value
when XPath::Expression
XPath.attr(attribute)[value]
when Regexp
XPath.attr(attribute)[regexp_to_xpath_conditions(value)]
when true
XPath.attr(attribute)
when false, nil
!XPath.attr(attribute)
else
XPath.attr(attribute) == value.to_s
end
end.reduce(:&)
end
def class_conditions(classes)
case classes
when XPath::Expression, Regexp
attribute_conditions(class: classes)
else
Array(classes).reject { |c| c.is_a? Regexp }.map do |klass|
if klass.match?(/^!(?!!!)/)
!XPath.attr(:class).contains_word(klass.slice(1..))
else
XPath.attr(:class).contains_word(klass.sub(/^!!/, ''))
end
end.reduce(:&)
end
end
def regexp_to_xpath_conditions(regexp)
condition = XPath.current
condition = condition.uppercase if regexp.casefold?
Selector::RegexpDisassembler.new(regexp).alternated_substrings.map do |strs|
strs.map { |str| condition.contains(str) }.reduce(:&)
end.reduce(:|)
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/builders/css_builder.rb | lib/capybara/selector/builders/css_builder.rb | # frozen_string_literal: true
require 'xpath'
module Capybara
class Selector
# @api private
class CSSBuilder
def initialize(expression)
@expression = expression || ''
end
attr_reader :expression
def add_attribute_conditions(**attributes)
@expression = attributes.inject(expression) do |css, (name, value)|
conditions = if name == :class
class_conditions(value)
elsif value.is_a? Regexp
regexp_conditions(name, value)
else
[attribute_conditions(name => value)]
end
::Capybara::Selector::CSS.split(css).map do |sel|
next sel if conditions.empty?
conditions.map { |cond| sel + cond }.join(', ')
end.join(', ')
end
end
private
def regexp_conditions(name, value)
Selector::RegexpDisassembler.new(value).alternated_substrings.map do |strs|
strs.map do |str|
"[#{name}*='#{str}'#{' i' if value.casefold?}]"
end.join
end
end
def attribute_conditions(attributes)
attributes.map do |attribute, value|
case value
when XPath::Expression
raise ArgumentError, "XPath expressions are not supported for the :#{attribute} filter with CSS based selectors"
when Regexp
Selector::RegexpDisassembler.new(value).substrings.map do |str|
"[#{attribute}*='#{str}'#{' i' if value.casefold?}]"
end.join
when true
"[#{attribute}]"
when false
':not([attribute])'
else
if attribute == :id
"##{::Capybara::Selector::CSS.escape(value)}"
else
"[#{attribute}='#{value}']"
end
end
end.join
end
def class_conditions(classes)
case classes
when XPath::Expression
raise ArgumentError, 'XPath expressions are not supported for the :class filter with CSS based selectors'
when Regexp
Selector::RegexpDisassembler.new(classes).alternated_substrings.map do |strs|
strs.map do |str|
"[class*='#{str}'#{' i' if classes.casefold?}]"
end.join
end
else
cls = Array(classes).reject { |c| c.is_a? Regexp }.group_by { |cl| cl.match?(/^!(?!!!)/) }
[(cls[false].to_a.map { |cl| ".#{Capybara::Selector::CSS.escape(cl.sub(/^!!/, ''))}" } +
cls[true].to_a.map { |cl| ":not(.#{Capybara::Selector::CSS.escape(cl.slice(1..))})" }).join]
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/queries/base_query.rb | lib/capybara/queries/base_query.rb | # frozen_string_literal: true
module Capybara
# @api private
module Queries
class BaseQuery
COUNT_KEYS = %i[count minimum maximum between].freeze
attr_reader :options
attr_writer :session_options
def initialize(options)
@session_options = options.delete(:session_options)
end
def session_options
@session_options || Capybara.session_options
end
def wait
self.class.wait(options, session_options.default_max_wait_time)
end
def self.wait(options, default = Capybara.default_max_wait_time)
# if no value or nil for the :wait option is passed it should default to the default
wait = options.fetch(:wait, nil)
wait = default if wait.nil?
wait || 0
end
##
#
# Checks if a count of 0 is valid for the query
# Returns false if query does not have any count options specified.
#
def expects_none?
count_specified? ? matches_count?(0) : false
end
##
#
# Checks if the given count matches the query count options.
# Defaults to true if no count options are specified. If multiple
# count options exist, it tests that all conditions are met;
# however, if :count is specified, all other options are ignored.
#
# @param [Integer] count The actual number. Should be coercible via Integer()
#
def matches_count?(count)
return (Integer(options[:count]) == count) if options[:count]
return false if options[:maximum] && (Integer(options[:maximum]) < count)
return false if options[:minimum] && (Integer(options[:minimum]) > count)
return false if options[:between] && !options[:between].include?(count)
true
end
##
#
# Generates a failure message from the query description and count options.
#
def failure_message
"expected to find #{description}" << count_message
end
def negative_failure_message
"expected not to find #{description}" << count_message
end
private
def count_specified?
COUNT_KEYS.any? { |key| options.key? key }
end
def count_message
message = +''
count, between, maximum, minimum = options.values_at(:count, :between, :maximum, :minimum)
if count
message << " #{occurrences count}"
elsif between
message << " between #{between.begin ? between.first : 1} and " \
"#{between.end ? between.last : 'infinite'} times"
elsif maximum
message << " at most #{occurrences maximum}"
elsif minimum
message << " at least #{occurrences minimum}"
end
message
end
def occurrences(count)
"#{count} #{Capybara::Helpers.declension('time', 'times', count)}"
end
def assert_valid_keys
invalid_keys = @options.keys - valid_keys
return if invalid_keys.empty?
invalid_names = invalid_keys.map(&:inspect).join(', ')
valid_names = valid_keys.map(&:inspect).join(', ')
raise ArgumentError, "Invalid option(s) #{invalid_names}, should be one of #{valid_names}"
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/queries/match_query.rb | lib/capybara/queries/match_query.rb | # frozen_string_literal: true
module Capybara
module Queries
class MatchQuery < Capybara::Queries::SelectorQuery
def visible
options.key?(:visible) ? super : :all
end
private
def assert_valid_keys
invalid_options = @options.keys & COUNT_KEYS
unless invalid_options.empty?
raise ArgumentError, "Match queries don't support quantity options. Invalid keys - #{invalid_options.join(', ')}"
end
super
end
def valid_keys
super - COUNT_KEYS
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/queries/sibling_query.rb | lib/capybara/queries/sibling_query.rb | # frozen_string_literal: true
module Capybara
module Queries
class SiblingQuery < SelectorQuery
# @api private
def resolve_for(node, exact = nil)
@sibling_node = node
node.synchronize do
scope = node.respond_to?(:session) ? node.session.current_scope : node.find(:xpath, '/*')
match_results = super(scope, exact)
siblings = node.find_xpath((XPath.preceding_sibling + XPath.following_sibling).to_s)
.map(&method(:to_element))
.select { |el| match_results.include?(el) }
Capybara::Result.new(ordered_results(siblings), self)
end
end
def description(applied = false) # rubocop:disable Style/OptionalBooleanParameter
desc = super
sibling_query = @sibling_node&.instance_variable_get(:@query)
desc += " that is a sibling of #{sibling_query.description}" if sibling_query
desc
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/queries/ancestor_query.rb | lib/capybara/queries/ancestor_query.rb | # frozen_string_literal: true
module Capybara
module Queries
class AncestorQuery < Capybara::Queries::SelectorQuery
# @api private
def resolve_for(node, exact = nil)
@child_node = node
node.synchronize do
scope = node.respond_to?(:session) ? node.session.current_scope : node.find(:xpath, '/*')
match_results = super(scope, exact)
ancestors = node.find_xpath(XPath.ancestor.to_s)
.map(&method(:to_element))
.select { |el| match_results.include?(el) }
Capybara::Result.new(ordered_results(ancestors), self)
end
end
def description(applied = false) # rubocop:disable Style/OptionalBooleanParameter
child_query = @child_node&.instance_variable_get(:@query)
desc = super
desc += " that is an ancestor of #{child_query.description}" if child_query
desc
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/queries/active_element_query.rb | lib/capybara/queries/active_element_query.rb | # frozen_string_literal: true
module Capybara
# @api private
module Queries
class ActiveElementQuery < BaseQuery
def initialize(**options)
@options = options
super(@options)
end
def resolve_for(session)
node = session.driver.active_element
[Capybara::Node::Element.new(session, node, nil, 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/queries/title_query.rb | lib/capybara/queries/title_query.rb | # frozen_string_literal: true
module Capybara
# @api private
module Queries
class TitleQuery < BaseQuery
def initialize(expected_title, **options)
@expected_title = expected_title.is_a?(Regexp) ? expected_title : expected_title.to_s
@options = options
super(@options)
@search_regexp = Helpers.to_regexp(@expected_title, all_whitespace: true, exact: options.fetch(:exact, false))
assert_valid_keys
end
def resolves_for?(node)
(@actual_title = node.title).match?(@search_regexp)
end
def failure_message
failure_message_helper
end
def negative_failure_message
failure_message_helper(' not')
end
private
def failure_message_helper(negated = '')
verb = @expected_title.is_a?(Regexp) ? 'match' : 'include'
"expected #{@actual_title.inspect}#{negated} to #{verb} #{@expected_title.inspect}"
end
def valid_keys
%i[wait exact]
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/queries/selector_query.rb | lib/capybara/queries/selector_query.rb | # frozen_string_literal: true
require 'matrix'
module Capybara
module Queries
class SelectorQuery < Queries::BaseQuery
attr_reader :expression, :selector, :locator, :options
SPATIAL_KEYS = %i[above below left_of right_of near].freeze
VALID_KEYS = SPATIAL_KEYS + COUNT_KEYS +
%i[text id class style visible obscured exact exact_text normalize_ws match wait filter_set focused]
VALID_MATCH = %i[first smart prefer_exact one].freeze
def initialize(*args,
session_options:,
enable_aria_label: session_options.enable_aria_label,
enable_aria_role: session_options.enable_aria_role,
test_id: session_options.test_id,
selector_format: nil,
order: nil,
**options,
&filter_block)
@resolved_node = nil
@resolved_count = 0
@options = options.dup
@order = order
@filter_cache = Hash.new { |hsh, key| hsh[key] = {} }
if @options[:text].is_a?(Regexp) && [true, false].include?(@options[:exact_text])
Capybara::Helpers.warn(
"Boolean 'exact_text' option is not supported when 'text' option is a Regexp - ignoring"
)
end
super(@options)
self.session_options = session_options
@selector = Selector.new(
find_selector(args[0].is_a?(Symbol) ? args.shift : args[0]),
config: {
enable_aria_label: enable_aria_label,
enable_aria_role: enable_aria_role,
test_id: test_id
},
format: selector_format
)
@locator = args.shift
@filter_block = filter_block
raise ArgumentError, "Unused parameters passed to #{self.class.name} : #{args}" unless args.empty?
@expression = selector.call(@locator, **@options)
warn_exact_usage
assert_valid_keys
end
def name; selector.name; end
def label; selector.label || selector.name; end
def description(only_applied = false) # rubocop:disable Style/OptionalBooleanParameter
desc = +''
show_for = show_for_stage(only_applied)
if show_for[:any]
desc << 'visible ' if visible == :visible
desc << 'non-visible ' if visible == :hidden
end
desc << label.to_s
desc << " #{locator.inspect}" unless locator.nil?
if show_for[:any]
desc << " with#{' exact' if exact_text == true} text #{options[:text].inspect}" if options[:text]
desc << " with exact text #{exact_text}" if exact_text.is_a?(String)
end
desc << " with id #{options[:id]}" if options[:id]
desc << " with classes [#{Array(options[:class]).join(',')}]" if options[:class]
desc << ' that is focused' if options[:focused]
desc << ' that is not focused' if options[:focused] == false
desc << case options[:style]
when String
" with style attribute #{options[:style].inspect}"
when Regexp
" with style attribute matching #{options[:style].inspect}"
when Hash
" with styles #{options[:style].inspect}"
else ''
end
%i[above below left_of right_of near].each do |spatial_filter|
if options[spatial_filter] && show_for[:spatial]
desc << " #{spatial_filter} #{options[spatial_filter] rescue '<ERROR>'}" # rubocop:disable Style/RescueModifier
end
end
desc << selector.description(node_filters: show_for[:node], **options)
desc << ' that also matches the custom filter block' if @filter_block && show_for[:node]
desc << " within #{@resolved_node.inspect}" if describe_within?
if locator.is_a?(String) && locator.start_with?('#', './/', '//') && !selector.raw_locator?
desc << "\nNote: It appears you may be passing a CSS selector or XPath expression rather than a locator. " \
"Please see the documentation for acceptable locator values.\n\n"
end
desc
end
def applied_description
description(true)
end
def matches_filters?(node, node_filter_errors = [])
return true if (@resolved_node&.== node) && options[:allow_self]
matches_locator_filter?(node) &&
matches_system_filters?(node) &&
matches_spatial_filters?(node) &&
matches_node_filters?(node, node_filter_errors) &&
matches_filter_block?(node)
rescue *(node.respond_to?(:session) ? node.session.driver.invalid_element_errors : [])
false
end
def visible
case (vis = options.fetch(:visible) { default_visibility })
when true then :visible
when false then :all
else vis
end
end
def exact?
supports_exact? ? options.fetch(:exact, session_options.exact) : false
end
def match
options.fetch(:match, session_options.match)
end
def xpath(exact = nil)
exact = exact? if exact.nil?
expr = apply_expression_filters(@expression)
expr = exact ? expr.to_xpath(:exact) : expr.to_s if expr.respond_to?(:to_xpath)
expr = filtered_expression(expr)
expr = "(#{expr})[#{xpath_text_conditions}]" if try_text_match_in_expression?
expr
end
def css
filtered_expression(apply_expression_filters(@expression))
end
# @api private
def resolve_for(node, exact = nil)
applied_filters.clear
@filter_cache.clear
@resolved_node = node
@resolved_count += 1
node.synchronize do
children = find_nodes_by_selector_format(node, exact).map(&method(:to_element))
Capybara::Result.new(ordered_results(children), self)
end
end
# @api private
def supports_exact?
return @expression.respond_to? :to_xpath if @selector.supports_exact?.nil?
@selector.supports_exact?
end
def failure_message
"expected to find #{applied_description}" << count_message
end
def negative_failure_message
"expected not to find #{applied_description}" << count_message
end
private
def selector_format
@selector.format
end
def matching_text
options[:text] || options[:exact_text]
end
def text_fragments
(text = matching_text).is_a?(String) ? text.split : []
end
def xpath_text_conditions
case (text = matching_text)
when String
text.split.map { |txt| XPath.contains(txt) }.reduce(&:&)
when Regexp
condition = XPath.current
condition = condition.uppercase if text.casefold?
Selector::RegexpDisassembler.new(text).alternated_substrings.map do |strs|
strs.flat_map(&:split).map { |str| condition.contains(str) }.reduce(:&)
end.reduce(:|)
end
end
def try_text_match_in_expression?
first_try? &&
matching_text &&
@resolved_node.is_a?(Capybara::Node::Base) &&
@resolved_node.session&.driver&.wait?
end
def first_try?
@resolved_count == 1
end
def show_for_stage(only_applied)
lambda do |stage = :any|
!only_applied || (stage == :any ? applied_filters.any? : applied_filters.include?(stage))
end
end
def applied_filters
@applied_filters ||= []
end
def find_selector(locator)
case locator
when Symbol then Selector[locator]
else Selector.for(locator)
end || Selector[session_options.default_selector]
end
def find_nodes_by_selector_format(node, exact)
hints = {}
hints[:uses_visibility] = true unless visible == :all
hints[:texts] = text_fragments unless selector_format == :xpath
hints[:styles] = options[:style] if use_default_style_filter?
hints[:position] = true if use_spatial_filter?
case selector_format
when :css
if node.method(:find_css).arity == 1
node.find_css(css)
else
node.find_css(css, **hints)
end
when :xpath
if node.method(:find_xpath).arity == 1
node.find_xpath(xpath(exact))
else
node.find_xpath(xpath(exact), **hints)
end
else
raise ArgumentError, "Unknown format: #{selector_format}"
end
end
def to_element(node)
if @resolved_node.is_a?(Capybara::Node::Base)
Capybara::Node::Element.new(@resolved_node.session, node, @resolved_node, self)
else
Capybara::Node::Simple.new(node)
end
end
def valid_keys
(VALID_KEYS + custom_keys).uniq
end
def matches_node_filters?(node, errors)
applied_filters << :node
unapplied_options = options.keys - valid_keys
@selector.with_filter_errors(errors) do
node_filters.all? do |filter_name, filter|
next true unless apply_filter?(filter)
if filter.matcher?
unapplied_options.select { |option_name| filter.handles_option?(option_name) }.all? do |option_name|
unapplied_options.delete(option_name)
filter.matches?(node, option_name, options[option_name], @selector)
end
elsif options.key?(filter_name)
unapplied_options.delete(filter_name)
filter.matches?(node, filter_name, options[filter_name], @selector)
elsif filter.default?
filter.matches?(node, filter_name, filter.default, @selector)
else
true
end
end
end
end
def matches_filter_block?(node)
return true unless @filter_block
if node.respond_to?(:session)
node.session.using_wait_time(0) { @filter_block.call(node) }
else
@filter_block.call(node)
end
end
def filter_set(name)
::Capybara::Selector::FilterSet[name]
end
def node_filters
if options.key?(:filter_set)
filter_set(options[:filter_set])
else
@selector
end.node_filters
end
def expression_filters
filters = @selector.expression_filters
filters.merge filter_set(options[:filter_set]).expression_filters if options.key?(:filter_set)
filters
end
def ordered_results(results)
case @order
when :reverse
results.reverse
else
results
end
end
def custom_keys
@custom_keys ||= node_filters.keys + expression_filters.keys
end
def assert_valid_keys
unless VALID_MATCH.include?(match)
raise ArgumentError, "Invalid option #{match.inspect} for :match, should be one of #{VALID_MATCH.map(&:inspect).join(', ')}"
end
unhandled_options = @options.keys.reject do |option_name|
valid_keys.include?(option_name) ||
expression_filters.any? { |_name, ef| ef.handles_option? option_name } ||
node_filters.any? { |_name, nf| nf.handles_option? option_name }
end
return if unhandled_options.empty?
invalid_names = unhandled_options.map(&:inspect).join(', ')
valid_names = (valid_keys - [:allow_self]).map(&:inspect).join(', ')
raise ArgumentError, "Invalid option(s) #{invalid_names}, should be one of #{valid_names}"
end
def filtered_expression(expr)
conditions = {}
conditions[:id] = options[:id] if use_default_id_filter?
conditions[:class] = options[:class] if use_default_class_filter?
conditions[:style] = options[:style] if use_default_style_filter? && !options[:style].is_a?(Hash)
builder(expr).add_attribute_conditions(**conditions)
end
def use_default_id_filter?
options.key?(:id) && !custom_keys.include?(:id)
end
def use_default_class_filter?
options.key?(:class) && !custom_keys.include?(:class)
end
def use_default_style_filter?
options.key?(:style) && !custom_keys.include?(:style)
end
def use_default_focused_filter?
options.key?(:focused) && !custom_keys.include?(:focused)
end
def use_spatial_filter?
options.values_at(*SPATIAL_KEYS).compact.any?
end
def apply_expression_filters(expression)
unapplied_options = options.keys - valid_keys
expression_filters.inject(expression) do |expr, (name, ef)|
next expr unless apply_filter?(ef)
if ef.matcher?
unapplied_options.select(&ef.method(:handles_option?)).inject(expr) do |memo, option_name|
unapplied_options.delete(option_name)
ef.apply_filter(memo, option_name, options[option_name], @selector)
end
elsif options.key?(name)
unapplied_options.delete(name)
ef.apply_filter(expr, name, options[name], @selector)
elsif ef.default?
ef.apply_filter(expr, name, ef.default, @selector)
else
expr
end
end
end
def warn_exact_usage
return unless options.key?(:exact) && !supports_exact?
warn "The :exact option only has an effect on queries using the XPath#is method. Using it with the query \"#{expression}\" has no effect."
end
def exact_text
options.fetch(:exact_text, session_options.exact_text)
end
def describe_within?
@resolved_node && !document?(@resolved_node) && !simple_root?(@resolved_node)
end
def document?(node)
node.is_a?(::Capybara::Node::Document)
end
def simple_root?(node)
node.is_a?(::Capybara::Node::Simple) && node.path == '/'
end
def apply_filter?(filter)
filter.format.nil? || (filter.format == selector_format)
end
def matches_locator_filter?(node)
return true unless @selector.locator_filter && apply_filter?(@selector.locator_filter)
@selector.locator_filter.matches?(node, @locator, @selector, exact: exact?)
end
def matches_system_filters?(node)
applied_filters << :system
matches_visibility_filters?(node) &&
matches_id_filter?(node) &&
matches_class_filter?(node) &&
matches_style_filter?(node) &&
matches_focused_filter?(node) &&
matches_text_filter?(node) &&
matches_exact_text_filter?(node)
end
def matches_spatial_filters?(node)
applied_filters << :spatial
return true unless use_spatial_filter?
node_rect = Rectangle.new(node.initial_cache[:position] || node.rect)
if options[:above]
el_rect = rect_cache(options[:above])
return false unless node_rect.above? el_rect
end
if options[:below]
el_rect = rect_cache(options[:below])
return false unless node_rect.below? el_rect
end
if options[:left_of]
el_rect = rect_cache(options[:left_of])
return false unless node_rect.left_of? el_rect
end
if options[:right_of]
el_rect = rect_cache(options[:right_of])
return false unless node_rect.right_of? el_rect
end
if options[:near]
return false if node == options[:near]
el_rect = rect_cache(options[:near])
return false unless node_rect.near? el_rect
end
true
end
def matches_id_filter?(node)
return true unless use_default_id_filter? && options[:id].is_a?(Regexp)
options[:id].match? node[:id]
end
def matches_class_filter?(node)
return true unless use_default_class_filter? && need_to_process_classes?
if options[:class].is_a? Regexp
options[:class].match? node[:class]
else
classes = (node[:class] || '').split
options[:class].select { |c| c.is_a? Regexp }.all? do |r|
classes.any? { |cls| r.match? cls }
end
end
end
def matches_focused_filter?(node)
return true unless use_default_focused_filter?
(node == node.session.active_element) == options[:focused]
end
def need_to_process_classes?
case options[:class]
when Regexp then true
when Array then options[:class].any?(Regexp)
else
false
end
end
def matches_style_filter?(node)
case options[:style]
when String, nil
true
when Regexp
options[:style].match? node[:style]
when Hash
matches_style?(node, options[:style])
end
end
def matches_style?(node, styles)
@actual_styles = node.initial_cache[:style] || node.style(*styles.keys)
styles.all? do |style, value|
if value.is_a? Regexp
value.match? @actual_styles[style.to_s]
else
@actual_styles[style.to_s] == value
end
end
end
def matches_text_filter?(node)
value = options[:text]
return true unless value
return matches_text_exactly?(node, value) if exact_text == true && !value.is_a?(Regexp)
regexp = value.is_a?(Regexp) ? value : Regexp.escape(value.to_s)
matches_text_regexp?(node, regexp)
end
def matches_exact_text_filter?(node)
case exact_text
when String, Regexp
matches_text_exactly?(node, exact_text)
else
true
end
end
def matches_visibility_filters?(node)
obscured = options[:obscured]
return (visible != :hidden) && (node.initial_cache[:visible] != false) && !node.obscured? if obscured == false
vis = case visible
when :visible
node.initial_cache[:visible] || (node.initial_cache[:visible].nil? && node.visible?)
when :hidden
# TODO: check why the 'visbile' cache spelling mistake wasn't caught in a test
# (node.initial_cache[:visible] == false) || (node.initial_cache[:visbile].nil? && !node.visible?)
(node.initial_cache[:visible] == false) || (node.initial_cache[:visible].nil? && !node.visible?)
else
true
end
vis && case obscured
when true
node.obscured?
when false
!node.obscured?
else
true
end
end
def matches_text_exactly?(node, value)
regexp = value.is_a?(Regexp) ? value : /\A#{Regexp.escape(value.to_s)}\z/
matches_text_regexp(node, regexp).then { |m| m&.pre_match == '' && m&.post_match == '' }
end
def normalize_ws
options.fetch(:normalize_ws, session_options.default_normalize_ws)
end
def matches_text_regexp(node, regexp)
text_visible = visible
text_visible = :all if text_visible == :hidden
node.text(text_visible, normalize_ws: normalize_ws).match(regexp)
end
def matches_text_regexp?(node, regexp)
!matches_text_regexp(node, regexp).nil?
end
def default_visibility
@selector.default_visibility(session_options.ignore_hidden_elements, options)
end
def builder(expr)
selector.builder(expr)
end
def position_cache(key)
@filter_cache[key][:position] ||= key.rect
end
def rect_cache(key)
@filter_cache[key][:rect] ||= Rectangle.new(position_cache(key))
end
class Rectangle
attr_reader :top, :bottom, :left, :right
def initialize(position)
# rubocop:disable Style/RescueModifier
@top = position['top'] rescue position['y']
@bottom = position['bottom'] rescue (@top + position['height'])
@left = position['left'] rescue position['x']
@right = position['right'] rescue (@left + position['width'])
# rubocop:enable Style/RescueModifier
end
def distance(other)
distance = Float::INFINITY
line_segments.each do |ls1|
other.line_segments.each do |ls2|
distance = [
distance,
distance_segment_segment(*ls1, *ls2)
].min
end
end
distance
end
def above?(other)
bottom <= other.top
end
def below?(other)
top >= other.bottom
end
def left_of?(other)
right <= other.left
end
def right_of?(other)
left >= other.right
end
def near?(other)
distance(other) <= 50
end
protected
def line_segments
[
[Vector[top, left], Vector[top, right]],
[Vector[top, right], Vector[bottom, left]],
[Vector[bottom, left], Vector[bottom, right]],
[Vector[bottom, right], Vector[top, left]]
]
end
private
def distance_segment_segment(l1p1, l1p2, l2p1, l2p2)
# See http://geomalgorithms.com/a07-_distance.html
# rubocop:disable Naming/VariableName
u = l1p2 - l1p1
v = l2p2 - l2p1
w = l1p1 - l2p1
a = u.dot u
b = u.dot v
c = v.dot v
d = u.dot w
e = v.dot w
cap_d = (a * c) - (b**2)
sD = tD = cap_d
# compute the line parameters of the two closest points
if cap_d < Float::EPSILON # the lines are almost parallel
sN = 0.0 # force using point P0 on segment S1
sD = 1.0 # to prevent possible division by 0.0 later
tN = e
tD = c
else # get the closest points on the infinite lines
sN = (b * e) - (c * d)
tN = (a * e) - (b * d)
if sN.negative? # sc < 0 => the s=0 edge is visible
sN = 0
tN = e
tD = c
elsif sN > sD # sc > 1 => the s=1 edge is visible
sN = sD
tN = e + b
tD = c
end
end
if tN.negative? # tc < 0 => the t=0 edge is visible
tN = 0
# recompute sc for this edge
if (-d).negative?
sN = 0.0
elsif -d > a
sN = sD
else
sN = -d
sD = a
end
elsif tN > tD # tc > 1 => the t=1 edge is visible
tN = tD
# recompute sc for this edge
if (-d + b).negative?
sN = 0.0
elsif (-d + b) > a
sN = sD
else
sN = (-d + b)
sD = a
end
end
# finally do the division to get sc and tc
sc = sN.abs < Float::EPSILON ? 0.0 : sN / sD
tc = tN.abs < Float::EPSILON ? 0.0 : tN / tD
# difference of the two closest points
dP = w + (u * sc) - (v * tc)
Math.sqrt(dP.dot(dP))
# rubocop:enable Naming/VariableName
end
end
private_constant :Rectangle
end
end
end
| ruby | MIT | b3325b198464b806f07ec2011ceb532d6d5cf4ab | 2026-01-04T15:38:10.098638Z | false |
teamcapybara/capybara | https://github.com/teamcapybara/capybara/blob/b3325b198464b806f07ec2011ceb532d6d5cf4ab/lib/capybara/queries/style_query.rb | lib/capybara/queries/style_query.rb | # frozen_string_literal: true
module Capybara
# @api private
module Queries
class StyleQuery < BaseQuery
def initialize(expected_styles, session_options:, **options)
@expected_styles = stringify_keys(expected_styles)
@options = options
@actual_styles = {}
super(@options)
self.session_options = session_options
assert_valid_keys
end
def resolves_for?(node)
@node = node
@actual_styles = node.style(*@expected_styles.keys)
@expected_styles.all? do |style, value|
if value.is_a? Regexp
value.match? @actual_styles[style]
else
@actual_styles[style] == value
end
end
end
def failure_message
"Expected node to have styles #{@expected_styles.inspect}. " \
"Actual styles were #{@actual_styles.inspect}"
end
private
def stringify_keys(hsh)
hsh.transform_keys(&:to_s)
end
def valid_keys
%i[wait]
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/queries/text_query.rb | lib/capybara/queries/text_query.rb | # frozen_string_literal: true
module Capybara
# @api private
module Queries
class TextQuery < BaseQuery
def initialize(type = nil, expected_text, session_options:, **options) # rubocop:disable Style/OptionalArguments
@type = type.nil? ? default_type : type
raise ArgumentError, "#{@type} is not a valid type for a text query" unless valid_types.include?(@type)
@options = options
super(@options)
self.session_options = session_options
if expected_text.nil? && !exact?
warn 'Checking for expected text of nil is confusing and/or pointless since it will always match. ' \
"Please specify a string or regexp instead. #{Capybara::Helpers.filter_backtrace(caller)}"
end
@expected_text = expected_text.is_a?(Regexp) ? expected_text : expected_text.to_s
@search_regexp = Capybara::Helpers.to_regexp(@expected_text, exact: exact?)
assert_valid_keys
end
def resolve_for(node)
@node = node
@actual_text = text
@count = @actual_text.scan(@search_regexp).size
end
def failure_message
super << build_message(true)
end
def negative_failure_message
super << build_message(false)
end
def description
if @expected_text.is_a?(Regexp)
"text matching #{@expected_text.inspect}"
else
"#{'exact ' if exact?}text #{@expected_text.inspect}"
end
end
private
def exact?
options.fetch(:exact, session_options.exact_text)
end
def build_message(report_on_invisible)
message = +''
unless (COUNT_KEYS & @options.keys).empty?
message << " but found #{@count} #{Capybara::Helpers.declension('time', 'times', @count)}"
end
message << " in #{@actual_text.inspect}"
details_message = []
details_message << case_insensitive_message if @node && check_case_insensitive?
details_message << invisible_message if @node && check_visible_text? && report_on_invisible
details_message.compact!
message << ". (However, #{details_message.join(' and ')}.)" unless details_message.empty?
message
end
def case_insensitive_message
insensitive_regexp = Capybara::Helpers.to_regexp(@expected_text, options: Regexp::IGNORECASE)
insensitive_count = @actual_text.scan(insensitive_regexp).size
return if insensitive_count == @count
"it was found #{occurrences insensitive_count} using a case insensitive search"
end
def invisible_message
invisible_text = text(query_type: :all)
invisible_count = invisible_text.scan(@search_regexp).size
return if invisible_count == @count
"it was found #{occurrences invisible_count} including non-visible text"
rescue StandardError
# An error getting the non-visible text (if element goes out of scope) should not affect the response
nil
end
def valid_keys
COUNT_KEYS + %i[wait exact normalize_ws]
end
def valid_types
%i[all visible]
end
def check_visible_text?
@type == :visible
end
def check_case_insensitive?
!@expected_text.is_a?(Regexp)
end
def text(node: @node, query_type: @type)
normalize_ws = options.fetch(:normalize_ws, session_options.default_normalize_ws)
node.text(query_type, normalize_ws: normalize_ws)
end
def default_type
Capybara.ignore_hidden_elements || Capybara.visible_text_only ? :visible : :all
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/queries/current_path_query.rb | lib/capybara/queries/current_path_query.rb | # frozen_string_literal: true
require 'addressable/uri'
module Capybara
# @api private
module Queries
class CurrentPathQuery < BaseQuery
def initialize(expected_path, **options, &optional_filter_block)
super(options)
@expected_path = expected_path
@options = {
url: !@expected_path.is_a?(Regexp) && !::Addressable::URI.parse(@expected_path || '').hostname.nil?,
ignore_query: false
}.merge(options)
@filter_block = optional_filter_block
assert_valid_keys
end
def resolves_for?(session)
uri = ::Addressable::URI.parse(session.current_url)
@actual_path = (options[:ignore_query] ? uri&.omit(:query) : uri).then do |u|
options[:url] ? u&.to_s : u&.request_uri
end
res = if @expected_path.is_a? Regexp
@actual_path.to_s.match?(@expected_path)
else
::Addressable::URI.parse(@expected_path) == ::Addressable::URI.parse(@actual_path)
end
res && matches_filter_block?(uri)
end
def failure_message
failure_message_helper
end
def negative_failure_message
failure_message_helper(' not')
end
private
def matches_filter_block?(url)
return true unless @filter_block
@filter_block.call(url)
end
def failure_message_helper(negated = '')
verb = @expected_path.is_a?(Regexp) ? 'match' : 'equal'
"expected #{@actual_path.inspect}#{negated} to #{verb} #{@expected_path.inspect}"
end
def valid_keys
%i[wait url ignore_query]
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/session/matchers.rb | lib/capybara/session/matchers.rb | # frozen_string_literal: true
module Capybara
module SessionMatchers
##
# Asserts that the page has the given path.
# By default, if passed a full url this will compare against the full url,
# if passed a path only the path+query portion will be compared, if passed a regexp
# the comparison will depend on the :url option (path+query by default)
#
# @!macro current_path_query_params
# @overload $0(string, **options)
# @param string [String] The string that the current 'path' should equal
# @overload $0(regexp, **options)
# @param regexp [Regexp] The regexp that the current 'path' should match to
# @option options [Boolean] :url (true if `string` is a full url, otherwise false) Whether the comparison should be done against the full current url or just the path
# @option options [Boolean] :ignore_query (false) Whether the query portion of the current url/path should be ignored
# @option options [Numeric] :wait (Capybara.default_max_wait_time) Maximum time that Capybara will wait for the current url/path to eq/match given string/regexp argument
# @raise [Capybara::ExpectationNotMet] if the assertion hasn't succeeded during wait time
# @return [true]
#
def assert_current_path(path, **options, &optional_filter_block)
_verify_current_path(path, optional_filter_block, **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 path.
# By default, if passed a full url this will compare against the full url,
# if passed a path only the path+query portion will be compared, if passed a regexp
# the comparison will depend on the :url option
#
# @macro current_path_query_params
# @raise [Capybara::ExpectationNotMet] if the assertion hasn't succeeded during wait time
# @return [true]
#
def assert_no_current_path(path, **options, &optional_filter_block)
_verify_current_path(path, optional_filter_block, **options) do |query|
raise Capybara::ExpectationNotMet, query.negative_failure_message if query.resolves_for?(self)
end
end
##
# Checks if the page has the given path.
# By default, if passed a full url this will compare against the full url,
# if passed a path only the path+query portion will be compared, if passed a regexp
# the comparison will depend on the :url option
#
# @macro current_path_query_params
# @return [Boolean]
#
def has_current_path?(path, **options, &optional_filter_block)
make_predicate(options) { assert_current_path(path, **options, &optional_filter_block) }
end
##
# Checks if the page doesn't have the given path.
# By default, if passed a full url this will compare against the full url,
# if passed a path only the path+query portion will be compared, if passed a regexp
# the comparison will depend on the :url option
#
# @macro current_path_query_params
# @return [Boolean]
#
def has_no_current_path?(path, **options, &optional_filter_block)
make_predicate(options) { assert_no_current_path(path, **options, &optional_filter_block) }
end
private
def _verify_current_path(path, filter_block, **options)
query = Capybara::Queries::CurrentPathQuery.new(path, **options, &filter_block)
document.synchronize(query.wait) do
yield(query)
end
true
end
def make_predicate(options)
options[:wait] = 0 unless options.key?(:wait) || config.predicates_wait
yield
rescue Capybara::ExpectationNotMet
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/session/config.rb | lib/capybara/session/config.rb | # frozen_string_literal: true
require 'delegate'
module Capybara
class SessionConfig
OPTIONS = %i[always_include_port run_server default_selector default_max_wait_time ignore_hidden_elements
automatic_reload match exact exact_text raise_server_errors visible_text_only
automatic_label_click enable_aria_label save_path asset_host default_host app_host
server_host server_port server_errors default_set_options disable_animation test_id
predicates_wait default_normalize_ws w3c_click_offset enable_aria_role default_retry_interval].freeze
attr_accessor(*OPTIONS)
##
# @!method always_include_port
# See {Capybara.configure}
# @!method run_server
# See {Capybara.configure}
# @!method default_selector
# See {Capybara.configure}
# @!method default_max_wait_time
# See {Capybara.configure}
# @!method default_retry_interval
# See {Capybara.configure}
# @!method ignore_hidden_elements
# See {Capybara.configure}
# @!method automatic_reload
# See {Capybara.configure}
# @!method match
# See {Capybara.configure}
# @!method exact
# See {Capybara.configure}
# @!method raise_server_errors
# See {Capybara.configure}
# @!method visible_text_only
# See {Capybara.configure}
# @!method automatic_label_click
# See {Capybara.configure}
# @!method enable_aria_label
# See {Capybara.configure}
# @!method enable_aria_role
# See {Capybara.configure}
# @!method save_path
# See {Capybara.configure}
# @!method asset_host
# See {Capybara.configure}
# @!method default_host
# See {Capybara.configure}
# @!method app_host
# See {Capybara.configure}
# @!method server_host
# See {Capybara.configure}
# @!method server_port
# See {Capybara.configure}
# @!method server_errors
# See {Capybara.configure}
# @!method default_set_options
# See {Capybara.configure}
# @!method disable_animation
# See {Capybara.configure}
# @!method test_id
# See {Capybara.configure}
# @!method default_normalize_ws
# See {Capybara.configure}
# @!method w3c_click_offset
# See {Capybara.configure}
remove_method :server_host
##
#
# @return [String] The IP address bound by default server
#
def server_host
@server_host || '127.0.0.1'
end
remove_method :server_errors=
def server_errors=(errors)
(@server_errors ||= []).replace(errors.dup)
end
remove_method :app_host=
def app_host=(url)
unless url.nil? || url.match?(URI::DEFAULT_PARSER.make_regexp)
raise ArgumentError, "Capybara.app_host should be set to a url (http://www.example.com). Attempted to set #{url.inspect}."
end
@app_host = url
end
remove_method :default_host=
def default_host=(url)
unless url.nil? || url.match?(URI::DEFAULT_PARSER.make_regexp)
raise ArgumentError, "Capybara.default_host should be set to a url (http://www.example.com). Attempted to set #{url.inspect}."
end
@default_host = url
end
remove_method :test_id=
##
#
# Set an attribute to be optionally matched against the locator for builtin selector types.
# This attribute will be checked by builtin selector types whenever id would normally be checked.
# If `nil` then it will be ignored.
#
# @param [String, Symbol, nil] id Name of the attribute to use as the test id
#
def test_id=(id)
@test_id = id&.to_sym
end
def initialize_copy(other)
super
@server_errors = @server_errors.dup
end
end
class ReadOnlySessionConfig < SimpleDelegator
SessionConfig::OPTIONS.each do |option|
define_method "#{option}=" do |_|
raise 'Per session settings are only supported when Capybara.threadsafe == 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/spec/test_app.rb | lib/capybara/spec/test_app.rb | # frozen_string_literal: true
require 'sinatra/base'
require 'tilt/erb'
require 'rack'
require 'yaml'
class TestApp < Sinatra::Base
class TestAppError < Exception; end # rubocop:disable Lint/InheritException
class TestAppOtherError < Exception # rubocop:disable Lint/InheritException
def initialize(string1, msg)
super()
@something = string1
@message = msg
end
end
set :root, File.dirname(__FILE__)
set :static, true
set :raise_errors, true
set :show_exceptions, false
set :host_authorization, { permitted_hosts: [] }
# Also check lib/capybara/spec/views/*.erb for pages not listed here
get '/' do
response.set_cookie('capybara', value: 'root cookie', domain: request.host, path: request.path)
'Hello world! <a href="with_html">Relative</a>'
end
get '/foo' do
'Another World'
end
get '/redirect' do
redirect '/redirect_again'
end
get '/redirect_with_fragment' do
redirect '/landed#with_fragment'
end
get '/redirect_again' do
redirect '/landed'
end
post '/redirect_307' do
redirect '/landed', 307
end
post '/redirect_308' do
redirect '/landed', 308
end
get '/referer_base' do
'<a href="/get_referer">direct link</a>' \
'<a href="/redirect_to_get_referer">link via redirect</a>' \
'<form action="/get_referer" method="get"><input type="submit"></form>'
end
get '/redirect_to_get_referer' do
redirect '/get_referer'
end
get '/get_referer' do
request.referer.nil? ? 'No referer' : "Got referer: #{request.referer}"
end
get '/host' do
"Current host is #{request.scheme}://#{request.host}:#{request.port}"
end
get '/redirect/:times/times' do
times = params[:times].to_i
if times.zero?
'redirection complete'
else
redirect "/redirect/#{times - 1}/times"
end
end
get '/landed' do
'You landed'
end
post '/landed' do
"You post landed: #{params.dig(:form, 'data')}"
end
get '/with-quotes' do
%q("No," he said, "you can't do that.")
end
get '/form/get' do
%(<pre id="results">#{params[:form].to_yaml}</pre>)
end
post '/relative' do
%(<pre id="results">#{params[:form].to_yaml}</pre>)
end
get '/favicon.ico' do
nil
end
post '/redirect' do
redirect '/redirect_again'
end
delete '/delete' do
'The requested object was deleted'
end
get '/delete' do
'Not deleted'
end
get '/redirect_back' do
redirect back
end
get '/redirect_secure' do
redirect "https://#{request.host}:#{request.port}/host"
end
get '/slow_response' do
sleep 2
'Finally!'
end
get '/set_cookie' do
cookie_value = 'test_cookie'
response.set_cookie('capybara', cookie_value)
"Cookie set to #{cookie_value}"
end
get '/get_cookie' do
request.cookies['capybara']
end
get '/get_header' do
env['HTTP_FOO']
end
get '/get_header_via_redirect' do
redirect '/get_header'
end
get '/error' do
raise TestAppError, 'some error'
end
get '/other_error' do
raise TestAppOtherError.new('something', 'other error')
end
get '/load_error' do
raise LoadError
end
get '/with.*html' do
erb :with_html, locals: { referrer: request.referrer }
end
get '/with_title' do
<<-HTML
<!DOCTYPE html>
<html lang="en">
<head>
<meta http-equiv="Content-type" content="text/html; charset=utf-8"/>
<title>#{params[:title] || 'Test Title'}</title>
</head>
<body>
<svg><title>abcdefg</title></svg>
</body>
</html>
HTML
end
get '/with_iframe' do
<<-HTML
<!DOCTYPE html>
<html lang="en">
<head>
<meta http-equiv="Content-type" content="text/html; charset=utf-8"/>
<title>Test with Iframe</title>
</head>
<body>
<iframe src="#{params[:url]}" id="#{params[:id]}"></iframe>
</body>
</html>
HTML
end
get '/base/with_base' do
<<-HTML
<!DOCTYPE html>
<html>
<head>
<base href="/">
<title>Origin</title>
</head>
<body>
<a href="with_title">Title page</a>
<a href="?a=3">Bare query</a>
</body>
</html>
HTML
end
get '/base/with_other_base' do
<<-HTML
<!DOCTYPE html>
<html>
<head>
<base href="/base/">
<title>Origin</title>
</head>
<body>
<a href="with_title">Title page</a>
<a href="?a=3">Bare query</a>
</body>
</html>
HTML
end
get '/csp' do
response.headers['Content-Security-Policy'] = "default-src 'none'; connect-src 'self'; base-uri 'none'; font-src 'self'; img-src 'self' data:; object-src 'none'; script-src 'self' 'nonce-jAviMuMisoTisVXjgLoWdA=='; style-src 'self' 'nonce-jAviMuMisoTisVXjgLoWdA=='; form-action 'self';"
<<-HTML
<!DOCTYPE html>
<html lang="en">
<head>
<meta http-equiv="Content-type" content="text/html; charset=utf-8"/>
<title>CSP</title>
</head>
<body>
<div>CSP</div>
</body>
</html>
HTML
end
get '/download.csv' do
content_type 'text/csv'
'This, is, comma, separated' \
'Thomas, Walpole, was , here'
end
get %r{/apple-touch-.*\.png/} do
halt(404)
end
get '/:view' do |view|
view_template = "#{__dir__}/views/#{view}.erb"
has_layout = File.exist?(view_template) && File.open(view_template) { |f| f.first.downcase.include?('doctype') }
erb view.to_sym, locals: { referrer: request.referrer }, layout: !has_layout
end
post '/form' do
self.class.form_post_count += 1
%(
<pre id="content_type">#{request.content_type}</pre>
<pre id="results">#{params.fetch(:form, {}).merge('post_count' => self.class.form_post_count).to_yaml}</pre>
)
end
post '/upload_empty' do
if params[:form][:file].nil?
"Successfully ignored empty file field. Content type was #{request.content_type}"
else
'Something went wrong.'
end
end
post '/upload' do
buffer = []
buffer << "Content-type: #{params.dig(:form, :document, :type)}"
buffer << "File content: #{params.dig(:form, :document, :tempfile).read}"
buffer.join(' | ')
rescue StandardError
'No file uploaded'
end
post '/upload_multiple' do
docs = params.dig(:form, :multiple_documents)
buffer = [docs.size.to_s]
docs.each do |doc|
buffer << "Content-type: #{doc[:type]}"
buffer << "File content: #{doc[:tempfile].read}"
end
buffer.join(' | ')
rescue StandardError
'No files uploaded'
end
class << self
attr_accessor :form_post_count
end
@form_post_count = 0
end
Rack::Handler::Puma.run TestApp, Port: 8070 if $PROGRAM_NAME == __FILE__
| ruby | MIT | b3325b198464b806f07ec2011ceb532d6d5cf4ab | 2026-01-04T15:38:10.098638Z | false |
teamcapybara/capybara | https://github.com/teamcapybara/capybara/blob/b3325b198464b806f07ec2011ceb532d6d5cf4ab/lib/capybara/spec/spec_helper.rb | lib/capybara/spec/spec_helper.rb | # frozen_string_literal: true
require 'rspec'
require 'rspec/expectations'
require 'capybara'
require 'capybara/rspec' # Required here instead of in rspec_spec to avoid RSpec deprecation warning
require 'capybara/spec/test_app'
require 'nokogiri'
Capybara.save_path = File.join(Dir.pwd, 'save_path_tmp')
module Capybara
module SpecHelper
class << self
def configure(config)
config.filter_run_excluding requires: method(:filter).to_proc
config.before { Capybara::SpecHelper.reset! }
config.after { Capybara::SpecHelper.reset! }
config.shared_context_metadata_behavior = :apply_to_host_groups
end
def reset!
Capybara.app = TestApp
Capybara.app_host = nil
Capybara.default_selector = :xpath
Capybara.default_max_wait_time = 1
Capybara.default_retry_interval = 0.01
Capybara.ignore_hidden_elements = true
Capybara.exact = false
Capybara.raise_server_errors = true
Capybara.visible_text_only = false
Capybara.match = :smart
Capybara.enable_aria_label = false
Capybara.enable_aria_role = false
Capybara.default_set_options = {}
Capybara.disable_animation = false
Capybara.test_id = nil
Capybara.predicates_wait = true
Capybara.default_normalize_ws = false
Capybara.use_html5_parsing = !ENV['HTML5_PARSING'].nil?
Capybara.w3c_click_offset = true
reset_threadsafe
end
def filter(requires, metadata)
if requires && metadata[:capybara_skip]
requires.any? do |require|
metadata[:capybara_skip].include?(require)
end
else
false
end
end
def spec(name, *options, &block)
@specs ||= []
@specs << [name, options, block]
end
def run_specs(session, name, **options, &filter_block)
specs = @specs
RSpec.describe Capybara::Session, name, options do
include Capybara::SpecHelper
include Capybara::RSpecMatchers
before do |example|
@session = session
instance_exec(example, &filter_block) if filter_block
end
after do
session.reset_session!
end
before :each, :psc do
SpecHelper.reset_threadsafe(bool: true, session: session)
end
after psc: true do
SpecHelper.reset_threadsafe(session: session)
end
before :each, :exact_false do
Capybara.exact = false
end
specs.each do |spec_name, spec_options, block|
describe spec_name, *spec_options do
class_eval(&block)
end
end
end
end
def reset_threadsafe(bool: false, session: nil)
# Work around limit on when threadsafe can be changed
Capybara::Session.class_variable_set(:@@instance_created, false) # rubocop:disable Style/ClassVars
Capybara.threadsafe = bool
session = session.current_session if session.respond_to?(:current_session)
session&.instance_variable_set(:@config, nil)
end
end
def silence_stream(stream)
old_stream = stream.dup
stream.reopen(RbConfig::CONFIG['host_os'].match?(/rmswin|mingw/) ? 'NUL:' : '/dev/null')
stream.sync = true
yield
ensure
stream.reopen(old_stream)
end
def quietly(&block)
silence_stream($stdout) do
silence_stream($stderr, &block)
end
end
def extract_results(session)
expect(session).to have_xpath("//pre[@id='results']")
perms = [(::Sinatra::IndifferentHash if defined? ::Sinatra::IndifferentHash)].compact
results = Capybara::HTML(session.body).xpath("//pre[@id='results']").first.inner_html.lstrip
YAML.safe_load results, permitted_classes: perms
end
def extract_content_type(session)
expect(session).to have_xpath("//pre[@id='content_type']")
Capybara::HTML(session.body).xpath("//pre[@id='content_type']").first.text
end
def be_an_invalid_element_error(session)
satisfy { |error| session.driver.invalid_element_errors.any? { |e| error.is_a? e } }
end
def with_os_path_separators(path)
Gem.win_platform? ? path.to_s.tr('/', '\\') : path.to_s
end
end
end
Dir["#{File.dirname(__FILE__)}/session/**/*.rb"].each { |file| require_relative file }
| ruby | MIT | b3325b198464b806f07ec2011ceb532d6d5cf4ab | 2026-01-04T15:38:10.098638Z | false |
teamcapybara/capybara | https://github.com/teamcapybara/capybara/blob/b3325b198464b806f07ec2011ceb532d6d5cf4ab/lib/capybara/spec/session/select_spec.rb | lib/capybara/spec/session/select_spec.rb | # frozen_string_literal: true
Capybara::SpecHelper.spec '#select' do
before do
@session.visit('/form')
end
it 'should return value of the first option' do
expect(@session.find_field('Title').value).to eq('Mrs')
end
it 'should return value of the selected option' do
@session.select('Miss', from: 'Title')
expect(@session.find_field('Title').value).to eq('Miss')
end
it 'should allow selecting exact options where there are inexact matches', :exact_false do
@session.select('Mr', from: 'Title')
expect(@session.find_field('Title').value).to eq('Mr')
end
it 'should allow selecting options where they are the only inexact match', :exact_false do
@session.select('Mis', from: 'Title')
expect(@session.find_field('Title').value).to eq('Miss')
end
it 'should not allow selecting options where they are the only inexact match if `exact: true` is specified' do
sel = @session.find(:select, 'Title')
expect do
sel.select('Mis', exact: true)
end.to raise_error(Capybara::ElementNotFound)
end
it 'should not allow selecting an option if the match is ambiguous', :exact_false do
expect do
@session.select('M', from: 'Title')
end.to raise_error(Capybara::Ambiguous)
end
it 'should return the value attribute rather than content if present' do
expect(@session.find_field('Locale').value).to eq('en')
end
it 'should select an option from a select box by id' do
@session.select('Finnish', from: 'form_locale')
@session.click_button('awesome')
expect(extract_results(@session)['locale']).to eq('fi')
end
it 'should select an option from a select box by label' do
@session.select('Finnish', from: 'Locale')
@session.click_button('awesome')
expect(extract_results(@session)['locale']).to eq('fi')
end
it 'should select an option without giving a select box' do
@session.select('Swedish')
@session.click_button('awesome')
expect(extract_results(@session)['locale']).to eq('sv')
end
it 'should escape quotes' do
@session.select("John's made-up language", from: 'Locale')
@session.click_button('awesome')
expect(extract_results(@session)['locale']).to eq('jo')
end
it 'should obey from' do
@session.select('Miss', from: 'Other title')
@session.click_button('awesome')
results = extract_results(@session)
expect(results['other_title']).to eq('Miss')
expect(results['title']).not_to eq('Miss')
end
it 'show match labels with preceding or trailing whitespace' do
@session.select('Lojban', from: 'Locale')
@session.click_button('awesome')
expect(extract_results(@session)['locale']).to eq('jbo')
end
it 'casts to string' do
@session.select(:Miss, from: :Title)
expect(@session.find_field('Title').value).to eq('Miss')
end
context 'input with datalist' do
it 'should select an option' do
@session.select('Audi', from: 'manufacturer')
@session.click_button('awesome')
expect(extract_results(@session)['manufacturer']).to eq('Audi')
end
it 'should not find an input without a datalist' do
expect do
@session.select('Thomas', from: 'form_first_name')
end.to raise_error(/Unable to find input box with datalist completion "form_first_name"/)
end
it "should not select an option that doesn't exist" do
expect do
@session.select('Tata', from: 'manufacturer')
end.to raise_error(/Unable to find datalist option "Tata"/)
end
it 'should not select a disabled option' do
expect do
@session.select('Mercedes', from: 'manufacturer')
end.to raise_error(/Unable to find datalist option "Mercedes"/)
end
end
context "with a locator that doesn't exist" do
it 'should raise an error' do
msg = /Unable to find select box "does not exist"/
expect do
@session.select('foo', from: 'does not exist')
end.to raise_error(Capybara::ElementNotFound, msg)
end
end
context "with an option that doesn't exist" do
it 'should raise an error' do
msg = /^Unable to find option "Does not Exist" within/
expect do
@session.select('Does not Exist', from: 'form_locale')
end.to raise_error(Capybara::ElementNotFound, msg)
end
end
context 'on a disabled select' do
it 'should raise an error' do
expect do
@session.select('Should not see me', from: 'Disabled Select')
end.to raise_error(Capybara::ElementNotFound)
end
end
context 'on a disabled option' do
it 'should not select' do
@session.select('Other', from: 'form_title')
expect(@session.find_field('form_title').value).not_to eq 'Other'
end
end
context 'with multiple select' do
it 'should return an empty value' do
expect(@session.find_field('Languages').value).to eq([])
end
it 'should return value of the selected options' do
@session.select('Ruby', from: 'Languages')
@session.select('Javascript', from: 'Languages')
expect(@session.find_field('Languages').value).to include('Ruby', 'Javascript')
end
it 'should select one option' do
@session.select('Ruby', from: 'Languages')
@session.click_button('awesome')
expect(extract_results(@session)['languages']).to eq(['Ruby'])
end
it 'should select multiple options' do
@session.select('Ruby', from: 'Languages')
@session.select('Javascript', from: 'Languages')
@session.click_button('awesome')
expect(extract_results(@session)['languages']).to include('Ruby', 'Javascript')
end
it 'should remain selected if already selected' do
@session.select('Ruby', from: 'Languages')
@session.select('Javascript', from: 'Languages')
@session.select('Ruby', from: 'Languages')
@session.click_button('awesome')
expect(extract_results(@session)['languages']).to include('Ruby', 'Javascript')
end
it 'should return value attribute rather than content if present' do
expect(@session.find_field('Underwear').value).to include('thermal')
end
end
context 'with :exact option' do
context 'when `false`' do
it 'can match select box approximately' do
@session.select('Finnish', from: 'Loc', exact: false)
@session.click_button('awesome')
expect(extract_results(@session)['locale']).to eq('fi')
end
it 'can match option approximately' do
@session.select('Fin', from: 'Locale', exact: false)
@session.click_button('awesome')
expect(extract_results(@session)['locale']).to eq('fi')
end
it 'can match option approximately when :from not given' do
@session.select('made-up language', exact: false)
@session.click_button('awesome')
expect(extract_results(@session)['locale']).to eq('jo')
end
end
context 'when `true`' do
it 'can match select box approximately' do
expect do
@session.select('Finnish', from: 'Loc', exact: true)
end.to raise_error(Capybara::ElementNotFound)
end
it 'can match option approximately' do
expect do
@session.select('Fin', from: 'Locale', exact: true)
end.to raise_error(Capybara::ElementNotFound)
end
it 'can match option approximately when :from not given' do
expect do
@session.select('made-up language', exact: true)
end.to raise_error(Capybara::ElementNotFound)
end
end
end
it 'should error when not passed a locator for :from option' do
select = @session.find(:select, 'Title')
expect { @session.select('Mr', from: select) }.to raise_error(ArgumentError, /does not take an element/)
end
end
| ruby | MIT | b3325b198464b806f07ec2011ceb532d6d5cf4ab | 2026-01-04T15:38:10.098638Z | false |
teamcapybara/capybara | https://github.com/teamcapybara/capybara/blob/b3325b198464b806f07ec2011ceb532d6d5cf4ab/lib/capybara/spec/session/find_field_spec.rb | lib/capybara/spec/session/find_field_spec.rb | # frozen_string_literal: true
Capybara::SpecHelper.spec '#find_field' do
before do
@session.visit('/form')
end
it 'should find any field' do
Capybara.test_id = 'data-test-id'
expect(@session.find_field('Dog').value).to eq('dog')
expect(@session.find_field('form_description').value).to eq('Descriptive text goes here')
expect(@session.find_field('Region')[:name]).to eq('form[region]')
expect(@session.find_field('With Asterisk*')).to be_truthy
expect(@session.find_field('my_test_id')).to be_truthy
end
context 'aria_label attribute with Capybara.enable_aria_label' do
it 'should find when true' do
Capybara.enable_aria_label = true
expect(@session.find_field('Unlabelled Input')[:name]).to eq('form[which_form]')
# expect(@session.find_field('Emergency Number')[:id]).to eq('html5_tel')
end
it 'should not find when false' do
Capybara.enable_aria_label = false
expect { @session.find_field('Unlabelled Input') }.to raise_error(Capybara::ElementNotFound)
# expect { @session.find_field('Emergency Number') }.to raise_error(Capybara::ElementNotFound)
end
end
it 'casts to string' do
expect(@session.find_field(:Dog).value).to eq('dog')
end
it "should raise error if the field doesn't exist" do
expect do
@session.find_field('Does not exist')
end.to raise_error(Capybara::ElementNotFound)
end
it 'should raise error if filter option is invalid' do
expect do
@session.find_field('Dog', disabled: nil)
end.to raise_error ArgumentError, 'Invalid value nil passed to NodeFilter disabled'
end
context 'with :exact option' do
it 'should accept partial matches when false' do
expect(@session.find_field('Explanation', exact: false)[:name]).to eq('form[name_explanation]')
end
it 'should not accept partial matches when true' do
expect do
@session.find_field('Explanation', exact: true)
end.to raise_error(Capybara::ElementNotFound)
end
end
context 'with :disabled option' do
it 'should find disabled fields when true' do
expect(@session.find_field('Disabled Checkbox', disabled: true)[:name]).to eq('form[disabled_checkbox]')
expect(@session.find_field('form_disabled_fieldset_child', disabled: true)[:name]).to eq('form[disabled_fieldset_child]')
expect(@session.find_field('form_disabled_fieldset_descendant', disabled: true)[:name]).to eq('form[disabled_fieldset_descendant]')
end
it 'should not find disabled fields when false' do
expect do
@session.find_field('Disabled Checkbox', disabled: false)
end.to raise_error(Capybara::ElementNotFound)
end
it 'should not find disabled fields by default' do
expect do
@session.find_field('Disabled Checkbox')
end.to raise_error(Capybara::ElementNotFound)
end
it 'should find disabled fields when :all' do
expect(@session.find_field('Disabled Checkbox', disabled: :all)[:name]).to eq('form[disabled_checkbox]')
end
it 'should find enabled fields when :all' do
expect(@session.find_field('Dog', disabled: :all).value).to eq('dog')
end
end
context 'with :readonly option' do
it 'should find readonly fields when true' do
expect(@session.find_field('form[readonly_test]', readonly: true)[:id]).to eq 'readonly'
end
it 'should not find readonly fields when false' do
expect(@session.find_field('form[readonly_test]', readonly: false)[:id]).to eq 'not_readonly'
end
it 'should ignore readonly by default' do
expect do
@session.find_field('form[readonly_test]')
end.to raise_error(Capybara::Ambiguous, /found 2 elements/)
end
end
context 'with no locator' do
it 'should use options to find the field' do
expect(@session.find_field(type: 'checkbox', with: 'dog')['id']).to eq 'form_pets_dog'
end
end
it 'should accept an optional filter block' do
# this would be better done with the :with option but this is just a test
expect(@session.find_field('form[pets][]') { |node| node.value == 'dog' }[:id]).to eq 'form_pets_dog'
end
end
| ruby | MIT | b3325b198464b806f07ec2011ceb532d6d5cf4ab | 2026-01-04T15:38:10.098638Z | false |
teamcapybara/capybara | https://github.com/teamcapybara/capybara/blob/b3325b198464b806f07ec2011ceb532d6d5cf4ab/lib/capybara/spec/session/current_scope_spec.rb | lib/capybara/spec/session/current_scope_spec.rb | # frozen_string_literal: true
Capybara::SpecHelper.spec '#current_scope' do
before do
@session.visit('/with_scope')
end
context 'when not in a #within block' do
it 'should return the document' do
expect(@session.current_scope).to be_a Capybara::Node::Document
end
end
context 'when in a #within block' do
it 'should return the element in scope' do
@session.within(:css, '#simple_first_name') do
expect(@session.current_scope[:name]).to eq 'first_name'
end
end
end
context 'when in a nested #within block' do
it 'should return the element in scope' do
@session.within("//div[@id='for_bar']") do
@session.within(".//input[@value='Peter']") do
expect(@session.current_scope[:name]).to eq 'form[first_name]'
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/spec/session/assert_selector_spec.rb | lib/capybara/spec/session/assert_selector_spec.rb | # frozen_string_literal: true
Capybara::SpecHelper.spec '#assert_selector' do
before do
@session.visit('/with_html')
end
it 'should be true if the given selector is on the page' do
@session.assert_selector(:xpath, '//p')
@session.assert_selector(:css, 'p a#foo')
@session.assert_selector("//p[contains(.,'est')]")
end
it 'should be false if the given selector is not on the page' do
expect { @session.assert_selector(:xpath, '//abbr') }.to raise_error(Capybara::ElementNotFound)
expect { @session.assert_selector(:css, 'p a#doesnotexist') }.to raise_error(Capybara::ElementNotFound)
expect { @session.assert_selector("//p[contains(.,'thisstringisnotonpage')]") }.to raise_error(Capybara::ElementNotFound)
end
it 'should use default selector' do
Capybara.default_selector = :css
expect { @session.assert_selector('p a#doesnotexist') }.to raise_error(Capybara::ElementNotFound)
@session.assert_selector('p a#foo')
end
it 'should respect scopes' do
@session.within "//p[@id='first']" do
@session.assert_selector(".//a[@id='foo']")
expect { @session.assert_selector(".//a[@id='red']") }.to raise_error(Capybara::ElementNotFound)
end
end
context 'with count' do
it 'should be true if the content is on the page the given number of times' do
@session.assert_selector('//p', count: 3)
@session.assert_selector("//p//a[@id='foo']", count: 1)
@session.assert_selector("//p[contains(.,'est')]", count: 1)
end
it 'should be false if the content is on the page the given number of times' do
expect { @session.assert_selector('//p', count: 6) }.to raise_error(Capybara::ElementNotFound)
expect { @session.assert_selector("//p//a[@id='foo']", count: 2) }.to raise_error(Capybara::ElementNotFound)
expect { @session.assert_selector("//p[contains(.,'est')]", count: 5) }.to raise_error(Capybara::ElementNotFound)
end
it "should be false if the content isn't on the page at all" do
expect { @session.assert_selector('//abbr', count: 2) }.to raise_error(Capybara::ElementNotFound)
expect { @session.assert_selector("//p//a[@id='doesnotexist']", count: 1) }.to raise_error(Capybara::ElementNotFound)
end
end
context 'with text' do
it 'should discard all matches where the given string is not contained' do
@session.assert_selector('//p//a', text: 'Redirect', count: 1)
expect { @session.assert_selector('//p', text: 'Doesnotexist') }.to raise_error(Capybara::ElementNotFound)
end
it 'should discard all matches where the given regexp is not matched' do
@session.assert_selector('//p//a', text: /re[dab]i/i, count: 1)
expect { @session.assert_selector('//p//a', text: /Red$/) }.to raise_error(Capybara::ElementNotFound)
end
end
context 'with wait', requires: [:js] do
it 'should find element if it appears before given wait duration' do
Capybara.using_wait_time(0.1) do
@session.visit('/with_js')
@session.click_link('Click me')
@session.assert_selector(:css, 'a#has-been-clicked', text: 'Has been clicked', wait: 2)
end
end
end
end
Capybara::SpecHelper.spec '#assert_no_selector' do
before do
@session.visit('/with_html')
end
it 'should be false if the given selector is on the page' do
expect { @session.assert_no_selector(:xpath, '//p') }.to raise_error(Capybara::ElementNotFound)
expect { @session.assert_no_selector(:css, 'p a#foo') }.to raise_error(Capybara::ElementNotFound)
expect { @session.assert_no_selector("//p[contains(.,'est')]") }.to raise_error(Capybara::ElementNotFound)
end
it 'should be true if the given selector is not on the page' do
@session.assert_no_selector(:xpath, '//abbr')
@session.assert_no_selector(:css, 'p a#doesnotexist')
@session.assert_no_selector("//p[contains(.,'thisstringisnotonpage')]")
end
it 'should use default selector' do
Capybara.default_selector = :css
@session.assert_no_selector('p a#doesnotexist')
expect { @session.assert_no_selector('p a#foo') }.to raise_error(Capybara::ElementNotFound)
end
it 'should respect scopes' do
@session.within "//p[@id='first']" do
expect { @session.assert_no_selector(".//a[@id='foo']") }.to raise_error(Capybara::ElementNotFound)
@session.assert_no_selector(".//a[@id='red']")
end
end
context 'with count' do
it 'should be false if the content is on the page the given number of times' do
expect { @session.assert_no_selector('//p', count: 3) }.to raise_error(Capybara::ElementNotFound)
expect { @session.assert_no_selector("//p//a[@id='foo']", count: 1) }.to raise_error(Capybara::ElementNotFound)
expect { @session.assert_no_selector("//p[contains(.,'est')]", count: 1) }.to raise_error(Capybara::ElementNotFound)
end
it 'should be true if the content is on the page the wrong number of times' do
@session.assert_no_selector('//p', count: 6)
@session.assert_no_selector("//p//a[@id='foo']", count: 2)
@session.assert_no_selector("//p[contains(.,'est')]", count: 5)
end
it "should be true if the content isn't on the page at all" do
@session.assert_no_selector('//abbr', count: 2)
@session.assert_no_selector("//p//a[@id='doesnotexist']", count: 1)
end
end
context 'with text' do
it 'should discard all matches where the given string is contained' do
expect { @session.assert_no_selector('//p//a', text: 'Redirect', count: 1) }.to raise_error(Capybara::ElementNotFound)
@session.assert_no_selector('//p', text: 'Doesnotexist')
end
it 'should discard all matches where the given regexp is matched' do
expect { @session.assert_no_selector('//p//a', text: /re[dab]i/i, count: 1) }.to raise_error(Capybara::ElementNotFound)
@session.assert_no_selector('//p//a', text: /Red$/)
end
end
context 'with wait', requires: [:js] do
it 'should not find element if it appears after given wait duration' do
@session.visit('/with_js')
@session.click_link('Click me')
@session.assert_no_selector(:css, 'a#has-been-clicked', text: 'Has been clicked', wait: 0.1)
end
end
end
| ruby | MIT | b3325b198464b806f07ec2011ceb532d6d5cf4ab | 2026-01-04T15:38:10.098638Z | false |
teamcapybara/capybara | https://github.com/teamcapybara/capybara/blob/b3325b198464b806f07ec2011ceb532d6d5cf4ab/lib/capybara/spec/session/execute_script_spec.rb | lib/capybara/spec/session/execute_script_spec.rb | # frozen_string_literal: true
Capybara::SpecHelper.spec '#execute_script', requires: [:js] do
it 'should execute the given script and return nothing' do
@session.visit('/with_js')
expect(@session.execute_script("document.getElementById('change').textContent = 'Funky Doodle'")).to be_nil
expect(@session).to have_css('#change', text: 'Funky Doodle')
end
it 'should be able to call functions defined in the page' do
@session.visit('/with_js')
expect { @session.execute_script("$('#change').text('Funky Doodle')") }.not_to raise_error
end
it 'should pass arguments to the script', requires: %i[js es_args] do
@session.visit('/with_js')
expect(@session).to have_css('#change')
@session.execute_script("document.getElementById('change').textContent = arguments[0]", 'Doodle Funk')
expect(@session).to have_css('#change', text: 'Doodle Funk')
end
it 'should support passing elements as arguments to the script', requires: %i[js es_args] do
@session.visit('/with_js')
el = @session.find(:css, '#change')
@session.execute_script('arguments[1].textContent = arguments[0]', 'Doodle Funk', el)
expect(@session).to have_css('#change', text: 'Doodle Funk')
end
end
| ruby | MIT | b3325b198464b806f07ec2011ceb532d6d5cf4ab | 2026-01-04T15:38:10.098638Z | false |
teamcapybara/capybara | https://github.com/teamcapybara/capybara/blob/b3325b198464b806f07ec2011ceb532d6d5cf4ab/lib/capybara/spec/session/find_by_id_spec.rb | lib/capybara/spec/session/find_by_id_spec.rb | # frozen_string_literal: true
Capybara::SpecHelper.spec '#find_by_id' do
before do
@session.visit('/with_html')
end
it 'should find any element by id' do
expect(@session.find_by_id('red').tag_name).to eq('a')
end
it 'casts to string' do
expect(@session.find_by_id(:red).tag_name).to eq('a')
end
it 'should raise error if no element with id is found' do
expect do
@session.find_by_id('nothing_with_this_id')
end.to raise_error(Capybara::ElementNotFound)
end
context 'with :visible option' do
it 'finds invisible elements when `false`' do
expect(@session.find_by_id('hidden_via_ancestor', visible: false).text(:all)).to match(/with hidden ancestor/)
end
it "doesn't find invisible elements when `true`" do
expect do
@session.find_by_id('hidden_via_ancestor', visible: true)
end.to raise_error(Capybara::ElementNotFound)
end
end
end
| ruby | MIT | b3325b198464b806f07ec2011ceb532d6d5cf4ab | 2026-01-04T15:38:10.098638Z | false |
teamcapybara/capybara | https://github.com/teamcapybara/capybara/blob/b3325b198464b806f07ec2011ceb532d6d5cf4ab/lib/capybara/spec/session/click_button_spec.rb | lib/capybara/spec/session/click_button_spec.rb | # frozen_string_literal: true
Capybara::SpecHelper.spec '#click_button' do
before do
@session.visit('/form')
end
it 'should wait for asynchronous load', requires: [:js] do
@session.visit('/with_js')
@session.using_wait_time(1.5) do
@session.click_link('Click me')
@session.click_button('New Here')
end
end
it 'casts to string' do
@session.click_button(:'Relative Action')
expect(extract_results(@session)['relative']).to eq('Relative Action')
expect(@session.current_path).to eq('/relative')
end
context 'with multiple values with the same name' do
it 'should use the latest given value' do
@session.check('Terms of Use')
@session.click_button('awesome')
expect(extract_results(@session)['terms_of_use']).to eq('1')
end
end
context 'with a form that has a relative url as an action' do
it 'should post to the correct url' do
@session.click_button('Relative Action')
expect(extract_results(@session)['relative']).to eq('Relative Action')
expect(@session.current_path).to eq('/relative')
end
end
context 'with a form that has no action specified' do
it 'should post to the correct url' do
@session.click_button('No Action')
expect(extract_results(@session)['no_action']).to eq('No Action')
expect(@session.current_path).to eq('/form')
end
end
context 'with value given on a submit button' do
context 'on a form with HTML5 fields' do
let(:results) { extract_results(@session) }
before do
@session.click_button('html5_submit')
end
it 'should serialise and submit search fields' do
expect(results['html5_search']).to eq('what are you looking for')
end
it 'should serialise and submit email fields' do
expect(results['html5_email']).to eq('person@email.com')
end
it 'should serialise and submit url fields' do
expect(results['html5_url']).to eq('http://www.example.com')
end
it 'should serialise and submit tel fields' do
expect(results['html5_tel']).to eq('911')
end
it 'should serialise and submit color fields' do
expect(results['html5_color'].upcase).to eq('#FFFFFF')
end
end
context 'on an HTML4 form' do
let(:results) { extract_results(@session) }
before do
@session.click_button('awesome')
end
it 'should serialize and submit text fields' do
expect(results['first_name']).to eq('John')
end
it 'should escape fields when submitting' do
expect(results['phone']).to eq('+1 555 7021')
end
it 'should serialize and submit password fields' do
expect(results['password']).to eq('seeekrit')
end
it 'should serialize and submit hidden fields' do
expect(results['token']).to eq('12345')
end
it 'should not serialize fields from other forms' do
expect(results['middle_name']).to be_nil
end
it 'should submit the button that was clicked, but not other buttons' do
expect(results['awesome']).to eq('awesome')
expect(results['crappy']).to be_nil
end
it 'should serialize radio buttons' do
expect(results['gender']).to eq('female')
end
it "should default radio value to 'on' if none specified" do
expect(results['valueless_radio']).to eq('on')
end
it 'should serialize check boxes' do
expect(results['pets']).to include('dog', 'hamster')
expect(results['pets']).not_to include('cat')
end
it "should default checkbox value to 'on' if none specififed" do
expect(results['valueless_checkbox']).to eq('on')
end
it 'should serialize text areas' do
expect(results['description']).to eq('Descriptive text goes here')
end
it 'should serialize select tag with values' do
expect(results['locale']).to eq('en')
end
it 'should serialize select tag without values' do
expect(results['region']).to eq('Norway')
end
it 'should serialize first option for select tag with no selection' do
expect(results['city']).to eq('London')
end
it 'should not serialize a select tag without options' do
expect(results['tendency']).to be_nil
end
it 'should convert lf to cr/lf in submitted textareas' do
expect(results['newline']).to eq("\r\nNew line after and before textarea tag\r\n")
end
it 'should not submit disabled fields' do
expect(results['disabled_text_field']).to be_nil
expect(results['disabled_textarea']).to be_nil
expect(results['disabled_checkbox']).to be_nil
expect(results['disabled_radio']).to be_nil
expect(results['disabled_select']).to be_nil
expect(results['disabled_file']).to be_nil
end
end
end
context 'input type=submit button' do
it 'should submit by button id' do
@session.click_button('awe123')
expect(extract_results(@session)['first_name']).to eq('John')
end
it 'should submit by specific button id' do
@session.click_button(id: 'awe123')
expect(extract_results(@session)['first_name']).to eq('John')
end
it 'should submit by button title' do
@session.click_button('What an Awesome Button')
expect(extract_results(@session)['first_name']).to eq('John')
end
it 'should submit by partial title', :exact_false do
@session.click_button('What an Awesome')
expect(extract_results(@session)['first_name']).to eq('John')
end
it 'should submit by button name' do
@session.click_button('form[awesome]')
expect(extract_results(@session)['first_name']).to eq('John')
end
it 'should submit by specific button name' do
@session.click_button(name: 'form[awesome]')
expect(extract_results(@session)['first_name']).to eq('John')
end
it 'should submit by specific button name regex' do
@session.click_button(name: /form\[awes.*\]/)
expect(extract_results(@session)['first_name']).to eq('John')
end
end
context 'when Capybara.enable_aria_role = true' do
it 'should click on a button role', requires: [:js] do
Capybara.enable_aria_role = true
@session.using_wait_time(1.5) do
@session.visit('/with_js')
@session.click_button('ARIA button')
expect(@session).to have_button('ARIA button has been clicked')
end
end
end
context 'with fields associated with the form using the form attribute', requires: [:form_attribute] do
let(:results) { extract_results(@session) }
before do
@session.click_button('submit_form1')
end
it 'should serialize and submit text fields' do
expect(results['outside_input']).to eq('outside_input')
end
it 'should serialize text areas' do
expect(results['outside_textarea']).to eq('Some text here')
end
it 'should serialize select tags' do
expect(results['outside_select']).to eq('Ruby')
end
it 'should not serliaze fields associated with a different form' do
expect(results['for_form2']).to be_nil
end
end
context 'with submit button outside the form defined by <button> tag', requires: [:form_attribute] do
let(:results) { extract_results(@session) }
before do
@session.click_button('outside_button')
end
it 'should submit the associated form' do
expect(results['which_form']).to eq('form2')
end
it 'should submit the button that was clicked, but not other buttons' do
expect(results['outside_button']).to eq('outside_button')
expect(results['unused']).to be_nil
end
end
context "with submit button outside the form defined by <input type='submit'> tag", requires: [:form_attribute] do
let(:results) { extract_results(@session) }
before do
@session.click_button('outside_submit')
end
it 'should submit the associated form' do
expect(results['which_form']).to eq('form1')
end
it 'should submit the button that was clicked, but not other buttons' do
expect(results['outside_submit']).to eq('outside_submit')
expect(results['submit_form1']).to be_nil
end
end
context 'with submit button for form1 located within form2', requires: [:form_attribute] do
it 'should submit the form associated with the button' do
@session.click_button('other_form_button')
expect(extract_results(@session)['which_form']).to eq('form1')
end
end
context 'with submit button not associated with any form' do
it 'should not error when clicked' do
expect { @session.click_button('no_form_button') }.not_to raise_error
end
end
context 'with alt given on an image button' do
it 'should submit the associated form' do
@session.click_button('oh hai thar')
expect(extract_results(@session)['first_name']).to eq('John')
end
it 'should work with partial matches', :exact_false do
@session.click_button('hai')
expect(extract_results(@session)['first_name']).to eq('John')
end
end
context 'with value given on an image button' do
it 'should submit the associated form' do
@session.click_button('okay')
expect(extract_results(@session)['first_name']).to eq('John')
end
it 'should work with partial matches', :exact_false do
@session.click_button('kay')
expect(extract_results(@session)['first_name']).to eq('John')
end
end
context 'with id given on an image button' do
it 'should submit the associated form' do
@session.click_button('okay556')
expect(extract_results(@session)['first_name']).to eq('John')
end
end
context 'with title given on an image button' do
it 'should submit the associated form' do
@session.click_button('Okay 556 Image')
expect(extract_results(@session)['first_name']).to eq('John')
end
it 'should work with partial matches', :exact_false do
@session.click_button('Okay 556')
expect(extract_results(@session)['first_name']).to eq('John')
end
end
context 'with text given on a button defined by <button> tag' do
it 'should submit the associated form' do
@session.click_button('Click me!')
expect(extract_results(@session)['first_name']).to eq('John')
end
it 'should work with partial matches', :exact_false do
@session.click_button('Click')
expect(extract_results(@session)['first_name']).to eq('John')
end
end
context 'with id given on a button defined by <button> tag' do
it 'should submit the associated form' do
@session.click_button('click_me_123')
expect(extract_results(@session)['first_name']).to eq('John')
end
it 'should serialize and send GET forms' do
@session.visit('/form')
@session.click_button('med')
results = extract_results(@session)
expect(results['middle_name']).to eq('Darren')
expect(results['foo']).to be_nil
end
end
context 'with name given on a button defined by <button> tag' do
it 'should submit the associated form when name is locator' do
@session.click_button('form[no_value]')
expect(extract_results(@session)['first_name']).to eq('John')
end
it 'should submit the associated form when name is specific' do
@session.click_button(name: 'form[no_value]')
expect(extract_results(@session)['first_name']).to eq('John')
end
end
context 'with value given on a button defined by <button> tag' do
it 'should submit the associated form' do
@session.click_button('click_me')
expect(extract_results(@session)['first_name']).to eq('John')
end
it 'should work with partial matches', :exact_false do
@session.click_button('ck_me')
expect(extract_results(@session)['first_name']).to eq('John')
end
end
context 'with title given on a button defined by <button> tag' do
it 'should submit the associated form' do
@session.click_button('Click Title button')
expect(extract_results(@session)['first_name']).to eq('John')
end
it 'should work with partial matches', :exact_false do
@session.click_button('Click Title')
expect(extract_results(@session)['first_name']).to eq('John')
end
end
context 'with descendant image alt given on a button defined by <button> tag' do
it 'should submit the associated form' do
@session.click_button('A horse eating hay')
expect(extract_results(@session)['first_name']).to eq('John')
end
it 'should work with partial matches', :exact_false do
@session.click_button('se eating h')
expect(extract_results(@session)['first_name']).to eq('John')
end
end
context "with a locator that doesn't exist" do
it 'should raise an error' do
msg = /Unable to find button "does not exist"/
expect do
@session.click_button('does not exist')
end.to raise_error(Capybara::ElementNotFound, msg)
end
end
context 'with formaction attribute on button' do
it 'should submit to the formaction attribute' do
@session.click_button('Formaction button')
results = extract_results(@session)
expect(@session.current_path).to eq '/form'
expect(results['which_form']).to eq 'formaction form'
end
end
context 'with formmethod attribute on button' do
it 'should submit to the formethod attribute' do
@session.click_button('Formmethod button')
results = extract_results(@session)
expect(@session.current_path).to eq '/form/get'
expect(results['which_form']).to eq 'formaction form'
end
end
it 'should serialize and send valueless buttons that were clicked' do
@session.click_button('No Value!')
results = extract_results(@session)
expect(results['no_value']).not_to be_nil
end
it 'should send button in document order' do
@session.click_button('outside_button')
results = extract_results(@session)
expect(results.keys).to eq %w[for_form2 outside_button which_form post_count]
end
it 'should not send image buttons that were not clicked' do
@session.click_button('Click me!')
results = extract_results(@session)
expect(results['okay']).to be_nil
end
it 'should serialize and send GET forms' do
@session.visit('/form')
@session.click_button('med')
results = extract_results(@session)
expect(results['middle_name']).to eq('Darren')
expect(results['foo']).to be_nil
end
it 'should follow redirects' do
@session.click_button('Go FAR')
expect(@session).to have_content('You landed')
expect(@session.current_url).to match(%r{/landed$})
end
it 'should follow temporary redirects that maintain method' do
@session.click_button('Go 307')
expect(@session).to have_content('You post landed: TWTW')
end
it 'should follow permanent redirects that maintain method' do
@session.click_button('Go 308')
expect(@session).to have_content('You post landed: TWTW')
end
it 'should post pack to the same URL when no action given' do
@session.visit('/postback')
@session.click_button('With no action')
expect(@session).to have_content('Postback')
end
it 'should post pack to the same URL when blank action given' do
@session.visit('/postback')
@session.click_button('With blank action')
expect(@session).to have_content('Postback')
end
it 'ignores disabled buttons' do
expect do
@session.click_button('Disabled button')
end.to raise_error(Capybara::ElementNotFound)
end
it 'should encode complex field names, like array[][value]' do
@session.visit('/form')
@session.fill_in('address1_city', with: 'Paris')
@session.fill_in('address1_street', with: 'CDG')
@session.fill_in('address2_city', with: 'Mikolaiv')
@session.fill_in('address2_street', with: 'PGS')
@session.click_button 'awesome'
addresses = extract_results(@session)['addresses']
expect(addresses.size).to eq(2)
expect(addresses[0]['street']).to eq('CDG')
expect(addresses[0]['city']).to eq('Paris')
expect(addresses[0]['country']).to eq('France')
expect(addresses[1]['street']).to eq('PGS')
expect(addresses[1]['city']).to eq('Mikolaiv')
expect(addresses[1]['country']).to eq('Ukraine')
end
context 'with :exact option' do
it 'should accept partial matches when false' do
@session.click_button('What an Awesome', exact: false)
expect(extract_results(@session)['first_name']).to eq('John')
end
it 'should not accept partial matches when true' do
expect do
@session.click_button('What an Awesome', exact: true)
end.to raise_error(Capybara::ElementNotFound)
end
end
it 'should work with popovers' do
@session.click_button('Show popover')
clickable = @session.find(:button, 'Should be clickable', visible: false)
expect(clickable).to be_visible
expect do
@session.click_button('Should be clickable')
end.not_to raise_error
end
end
| ruby | MIT | b3325b198464b806f07ec2011ceb532d6d5cf4ab | 2026-01-04T15:38:10.098638Z | false |
teamcapybara/capybara | https://github.com/teamcapybara/capybara/blob/b3325b198464b806f07ec2011ceb532d6d5cf4ab/lib/capybara/spec/session/find_button_spec.rb | lib/capybara/spec/session/find_button_spec.rb | # frozen_string_literal: true
Capybara::SpecHelper.spec '#find_button' do
before do
@session.visit('/form')
end
it 'should find any button' do
expect(@session.find_button('med')[:id]).to eq('mediocre')
expect(@session.find_button('crap321').value).to eq('crappy')
end
context 'aria_label attribute with Capybara.enable_aria_label' do
it 'should find when true' do
Capybara.enable_aria_label = true
expect(@session.find_button('Mediocre Button')[:id]).to eq('mediocre')
end
it 'should not find when false' do
Capybara.enable_aria_label = false
expect { @session.find_button('Mediocre Button') }.to raise_error(Capybara::ElementNotFound)
end
end
it 'casts to string' do
expect(@session.find_button(:med)[:id]).to eq('mediocre')
end
it "should raise error if the button doesn't exist" do
expect do
@session.find_button('Does not exist')
end.to raise_error(Capybara::ElementNotFound)
end
context 'with :exact option' do
it 'should accept partial matches when false' do
expect(@session.find_button('What an Awesome', exact: false).value).to eq('awesome')
end
it 'should not accept partial matches when true' do
expect do
@session.find_button('What an Awesome', exact: true)
end.to raise_error(Capybara::ElementNotFound)
end
end
context 'with :disabled option' do
it 'should find disabled buttons when true' do
expect(@session.find_button('Disabled button', disabled: true).value).to eq('Disabled button')
end
it 'should not find disabled buttons when false' do
expect do
@session.find_button('Disabled button', disabled: false)
end.to raise_error(Capybara::ElementNotFound)
end
it 'should default to not finding disabled buttons' do
expect do
@session.find_button('Disabled button')
end.to raise_error(Capybara::ElementNotFound)
end
it 'should find disabled buttons when :all' do
expect(@session.find_button('Disabled button', disabled: :all).value).to eq('Disabled button')
end
end
context 'without locator' do
it 'should use options' do
expect(@session.find_button(disabled: true).value).to eq('Disabled button')
end
end
end
| ruby | MIT | b3325b198464b806f07ec2011ceb532d6d5cf4ab | 2026-01-04T15:38:10.098638Z | false |
teamcapybara/capybara | https://github.com/teamcapybara/capybara/blob/b3325b198464b806f07ec2011ceb532d6d5cf4ab/lib/capybara/spec/session/evaluate_script_spec.rb | lib/capybara/spec/session/evaluate_script_spec.rb | # frozen_string_literal: true
Capybara::SpecHelper.spec '#evaluate_script', requires: [:js] do
it 'should evaluate the given script and return whatever it produces' do
@session.visit('/with_js')
expect(@session.evaluate_script('1+3')).to eq(4)
end
it 'should ignore leading whitespace' do
@session.visit('/with_js')
expect(@session.evaluate_script('
1 + 3
')).to eq(4)
end
it 'should pass arguments to the script', requires: %i[js es_args] do
@session.visit('/with_js')
expect(@session).to have_css('#change')
@session.evaluate_script("document.getElementById('change').textContent = arguments[0]", 'Doodle Funk')
expect(@session).to have_css('#change', text: 'Doodle Funk')
end
it 'should support passing elements as arguments to the script', requires: %i[js es_args] do
@session.visit('/with_js')
el = @session.find(:css, '#change')
@session.evaluate_script('arguments[0].textContent = arguments[1]', el, 'Doodle Funk')
expect(@session).to have_css('#change', text: 'Doodle Funk')
end
it 'should support returning elements', requires: %i[js es_args] do
@session.visit('/with_js')
@session.find(:css, '#change') # ensure page has loaded and element is available
el = @session.evaluate_script("document.getElementById('change')")
expect(el).to be_instance_of(Capybara::Node::Element)
expect(el).to eq(@session.find(:css, '#change'))
end
it 'should support multi statement via IIFE' do
@session.visit('/with_js')
@session.find(:css, '#change')
el = @session.evaluate_script(<<~JS)
(function(){
var el = document.getElementById('change');
return el;
})()
JS
expect(el).to eq(@session.find(:css, '#change'))
end
end
| ruby | MIT | b3325b198464b806f07ec2011ceb532d6d5cf4ab | 2026-01-04T15:38:10.098638Z | false |
teamcapybara/capybara | https://github.com/teamcapybara/capybara/blob/b3325b198464b806f07ec2011ceb532d6d5cf4ab/lib/capybara/spec/session/find_link_spec.rb | lib/capybara/spec/session/find_link_spec.rb | # frozen_string_literal: true
Capybara::SpecHelper.spec '#find_link' do
before do
@session.visit('/with_html')
end
it 'should find any link' do
expect(@session.find_link('foo').text).to eq('ullamco')
expect(@session.find_link('labore')[:href]).to match %r{/with_simple_html$}
end
context 'aria_label attribute with Capybara.enable_aria_label' do
it 'should find when true' do
Capybara.enable_aria_label = true
expect(@session.find_link('Go to simple')[:href]).to match %r{/with_simple_html$}
end
it 'should not find when false' do
Capybara.enable_aria_label = false
expect { @session.find_link('Go to simple') }.to raise_error(Capybara::ElementNotFound)
end
end
it 'casts to string' do
expect(@session.find_link(:foo).text).to eq('ullamco')
end
it "should raise error if the field doesn't exist" do
expect do
@session.find_link('Does not exist')
end.to raise_error(Capybara::ElementNotFound)
end
context 'with :exact option' do
it 'should accept partial matches when false' do
expect(@session.find_link('abo', exact: false).text).to eq('labore')
end
it 'should not accept partial matches when true' do
expect do
@session.find_link('abo', exact: true)
end.to raise_error(Capybara::ElementNotFound)
end
end
context 'without locator' do
it 'should use options' do
expect(@session.find_link(href: '#anchor').text).to eq 'Normal Anchor'
end
end
context 'download filter' do
it 'finds a download link' do
expect(@session.find_link('Download Me', download: true).text).to eq 'Download Me'
end
it "doesn't find a download link if download is false" do
expect { @session.find_link('Download Me', download: false) }.to raise_error Capybara::ElementNotFound
end
it 'finds a renaming download link' do
expect(@session.find_link(download: 'other.csv').text).to eq 'Download Other'
end
it 'raises if passed an invalid value' do
expect { @session.find_link(download: 37) }.to raise_error ArgumentError
end
end
context 'with :target option' do
it 'should accept partial matches when false' do
expect(@session.find_link(target: '_self').text).to eq('labore')
end
it 'should not accept partial matches when true' do
expect { @session.find_link(target: '_blank') }.to raise_error Capybara::ElementNotFound
end
end
end
| ruby | MIT | b3325b198464b806f07ec2011ceb532d6d5cf4ab | 2026-01-04T15:38:10.098638Z | false |
teamcapybara/capybara | https://github.com/teamcapybara/capybara/blob/b3325b198464b806f07ec2011ceb532d6d5cf4ab/lib/capybara/spec/session/choose_spec.rb | lib/capybara/spec/session/choose_spec.rb | # frozen_string_literal: true
Capybara::SpecHelper.spec '#choose' do
before do
@session.visit('/form')
end
it 'should choose a radio button by id' do
@session.choose('gender_male')
@session.click_button('awesome')
expect(extract_results(@session)['gender']).to eq('male')
end
it 'ignores readonly attribute on radio buttons' do
@session.choose('gender_both')
@session.click_button('awesome')
expect(extract_results(@session)['gender']).to eq('both')
end
it 'should choose a radio button by label' do
@session.choose('Both')
@session.click_button('awesome')
expect(extract_results(@session)['gender']).to eq('both')
end
it 'should work without a locator string' do
@session.choose(id: 'gender_male')
@session.click_button('awesome')
expect(extract_results(@session)['gender']).to eq('male')
end
it 'should be able to choose self when no locator string specified' do
rb = @session.find(:id, 'gender_male')
rb.choose
@session.click_button('awesome')
expect(extract_results(@session)['gender']).to eq('male')
end
it 'casts to string' do
@session.choose('Both')
@session.click_button(:awesome)
expect(extract_results(@session)['gender']).to eq('both')
end
context "with a locator that doesn't exist" do
it 'should raise an error' do
msg = /Unable to find radio button "does not exist"/
expect do
@session.choose('does not exist')
end.to raise_error(Capybara::ElementNotFound, msg)
end
end
context 'with a disabled radio button' do
it 'should raise an error' do
expect do
@session.choose('Disabled Radio')
end.to raise_error(Capybara::ElementNotFound)
end
end
context 'with :exact option' do
it 'should accept partial matches when false' do
@session.choose('Mal', exact: false)
@session.click_button('awesome')
expect(extract_results(@session)['gender']).to eq('male')
end
it 'should not accept partial matches when true' do
expect do
@session.choose('Mal', exact: true)
end.to raise_error(Capybara::ElementNotFound)
end
end
context 'with `option` option' do
it 'can check radio buttons by their value' do
@session.choose('form[gender]', option: 'male')
@session.click_button('awesome')
expect(extract_results(@session)['gender']).to eq('male')
end
it 'should alias `:with` option' do
@session.choose('form[gender]', with: 'male')
@session.click_button('awesome')
expect(extract_results(@session)['gender']).to eq('male')
end
it 'should raise an error if option not found' do
expect do
@session.choose('form[gender]', option: 'hermaphrodite')
end.to raise_error(Capybara::ElementNotFound)
end
end
context 'with hidden radio buttons' do
context 'with Capybara.automatic_label_click == true' do
around do |spec|
old_click_label, Capybara.automatic_label_click = Capybara.automatic_label_click, true
spec.run
Capybara.automatic_label_click = old_click_label
end
it 'should select by clicking the label if available' do
@session.choose('party_democrat')
@session.click_button('awesome')
expect(extract_results(@session)['party']).to eq('democrat')
end
it 'should select self by clicking the label if no locator specified' do
cb = @session.find(:id, 'party_democrat', visible: :hidden)
cb.choose
@session.click_button('awesome')
expect(extract_results(@session)['party']).to eq('democrat')
end
it 'should raise error if not allowed to click label' do
expect { @session.choose('party_democrat', allow_label_click: false) }.to raise_error(Capybara::ElementNotFound, /Unable to find visible radio button "party_democrat"/)
end
end
end
it 'should return the chosen radio button' do
el = @session.find(:radio_button, 'gender_male')
expect(@session.choose('gender_male')).to eq el
end
end
| ruby | MIT | b3325b198464b806f07ec2011ceb532d6d5cf4ab | 2026-01-04T15:38:10.098638Z | false |
teamcapybara/capybara | https://github.com/teamcapybara/capybara/blob/b3325b198464b806f07ec2011ceb532d6d5cf4ab/lib/capybara/spec/session/text_spec.rb | lib/capybara/spec/session/text_spec.rb | # frozen_string_literal: true
Capybara::SpecHelper.spec '#text' do
it 'should print the text of the page' do
@session.visit('/with_simple_html')
expect(@session.text).to eq('Bar')
end
it 'ignores invisible text by default' do
@session.visit('/with_html')
expect(@session.find(:id, 'hidden-text').text).to eq('Some of this text is')
end
it 'shows invisible text if `:all` given' do
@session.visit('/with_html')
expect(@session.find(:id, 'hidden-text').text(:all)).to eq('Some of this text is hidden!')
end
it 'ignores invisible text if `:visible` given' do
Capybara.ignore_hidden_elements = false
@session.visit('/with_html')
expect(@session.find(:id, 'hidden-text').text(:visible)).to eq('Some of this text is')
end
it 'ignores invisible text if `Capybara.ignore_hidden_elements = true`' do
@session.visit('/with_html')
expect(@session.find(:id, 'hidden-text').text).to eq('Some of this text is')
Capybara.ignore_hidden_elements = false
expect(@session.find(:id, 'hidden-text').text).to eq('Some of this text is hidden!')
end
it 'ignores invisible text if `Capybara.visible_text_only = true`' do
@session.visit('/with_html')
Capybara.visible_text_only = true
expect(@session.find(:id, 'hidden-text').text).to eq('Some of this text is')
Capybara.ignore_hidden_elements = false
expect(@session.find(:id, 'hidden-text').text).to eq('Some of this text is')
end
it 'ignores invisible text if ancestor is invisible' do
@session.visit('/with_html')
expect(@session.find(:id, 'hidden_via_ancestor', visible: false).text).to eq('')
end
context 'with css as default selector' do
before { Capybara.default_selector = :css }
after { Capybara.default_selector = :xpath }
it 'should print the text of the page' do
@session.visit('/with_simple_html')
expect(@session.text).to eq('Bar')
end
end
it 'should be correctly normalized when visible' do
@session.visit('/with_html')
el = @session.find(:css, '#normalized')
expect(el.text).to eq "Some text\nMore text\nAnd more text\nEven more text on multiple lines"
end
it 'should be a textContent with irrelevant whitespace collapsed when non-visible' do
@session.visit('/with_html')
el = @session.find(:css, '#non_visible_normalized', visible: false)
expect(el.text(:all)).to eq 'Some textMore text And more text Even more text on multiple lines'
end
it 'should strip correctly' do
@session.visit('/with_html')
el = @session.find(:css, '#ws')
expect(el.text).to eq ' '
expect(el.text(:all)).to eq ' '
end
end
| ruby | MIT | b3325b198464b806f07ec2011ceb532d6d5cf4ab | 2026-01-04T15:38:10.098638Z | false |
teamcapybara/capybara | https://github.com/teamcapybara/capybara/blob/b3325b198464b806f07ec2011ceb532d6d5cf4ab/lib/capybara/spec/session/active_element_spec.rb | lib/capybara/spec/session/active_element_spec.rb | # frozen_string_literal: true
Capybara::SpecHelper.spec '#active_element', requires: [:active_element] do
it 'should return the active element' do
@session.visit('/form')
@session.send_keys(:tab)
expect(@session.active_element).to match_selector(:css, '[tabindex="1"]')
@session.send_keys(:tab)
expect(@session.active_element).to match_selector(:css, '[tabindex="2"]')
end
it 'should support reloading' do
@session.visit('/form')
expect(@session.active_element).to match_selector(:css, 'body')
@session.execute_script <<-JS
window.setTimeout(() => {
document.querySelector('#form_title').focus();
}, 1000)
JS
expect(@session.active_element).to match_selector(:css, 'body', wait: false)
expect(@session.active_element).to match_selector(:css, '#form_title', wait: 2)
end
it 'should return a Capybara::Element' do
@session.visit('/form')
expect(@session.active_element).to be_a Capybara::Node::Element
end
end
| ruby | MIT | b3325b198464b806f07ec2011ceb532d6d5cf4ab | 2026-01-04T15:38:10.098638Z | false |
teamcapybara/capybara | https://github.com/teamcapybara/capybara/blob/b3325b198464b806f07ec2011ceb532d6d5cf4ab/lib/capybara/spec/session/first_spec.rb | lib/capybara/spec/session/first_spec.rb | # frozen_string_literal: true
Capybara::SpecHelper.spec '#first' do
before do
@session.visit('/with_html')
end
it 'should find the first element using the given locator' do
expect(@session.first('//h1').text).to eq('This is a test')
expect(@session.first("//input[@id='test_field']").value).to eq('monkey')
end
it 'should raise ElementNotFound when nothing was found' do
expect do
@session.first('//div[@id="nosuchthing"]')
end.to raise_error Capybara::ElementNotFound
end
it 'should return nil when nothing was found if count options allow no results' do
expect(@session.first('//div[@id="nosuchthing"]', minimum: 0)).to be_nil
expect(@session.first('//div[@id="nosuchthing"]', count: 0)).to be_nil
expect(@session.first('//div[@id="nosuchthing"]', between: (0..3))).to be_nil
end
it 'should accept an XPath instance' do
@session.visit('/form')
@xpath = Capybara::Selector.new(:fillable_field, config: {}, format: :xpath).call('First Name')
expect(@xpath).to be_a(XPath::Union)
expect(@session.first(@xpath).value).to eq('John')
end
it 'should raise when unused parameters are passed' do
expect do
@session.first(:css, 'h1', 'unused text')
end.to raise_error ArgumentError, /Unused parameters passed.*unused text/
end
context 'with css selectors' do
it 'should find the first element using the given selector' do
expect(@session.first(:css, 'h1').text).to eq('This is a test')
expect(@session.first(:css, "input[id='test_field']").value).to eq('monkey')
end
end
context 'with xpath selectors' do
it 'should find the first element using the given locator' do
expect(@session.first(:xpath, '//h1').text).to eq('This is a test')
expect(@session.first(:xpath, "//input[@id='test_field']").value).to eq('monkey')
end
end
context 'with css as default selector' do
before { Capybara.default_selector = :css }
it 'should find the first element using the given locator' do
expect(@session.first('h1').text).to eq('This is a test')
expect(@session.first("input[id='test_field']").value).to eq('monkey')
end
end
context 'with visible filter' do
it 'should only find visible nodes when true' do
expect do
@session.first(:css, 'a#invisible', visible: true)
end.to raise_error Capybara::ElementNotFound
end
it 'should find nodes regardless of whether they are invisible when false' do
expect(@session.first(:css, 'a#invisible', visible: false)).to be_truthy
expect(@session.first(:css, 'a#invisible', visible: false, text: 'hidden link')).to be_truthy
expect(@session.first(:css, 'a#visible', visible: false)).to be_truthy
end
it 'should find nodes regardless of whether they are invisible when :all' do
expect(@session.first(:css, 'a#invisible', visible: :all)).to be_truthy
expect(@session.first(:css, 'a#invisible', visible: :all, text: 'hidden link')).to be_truthy
expect(@session.first(:css, 'a#visible', visible: :all)).to be_truthy
end
it 'should find only hidden nodes when :hidden' do
expect(@session.first(:css, 'a#invisible', visible: :hidden)).to be_truthy
expect(@session.first(:css, 'a#invisible', visible: :hidden, text: 'hidden link')).to be_truthy
expect do
@session.first(:css, 'a#invisible', visible: :hidden, text: 'not hidden link')
end.to raise_error Capybara::ElementNotFound
expect do
@session.first(:css, 'a#visible', visible: :hidden)
end.to raise_error Capybara::ElementNotFound
end
it 'should find only visible nodes when :visible' do
expect do
@session.first(:css, 'a#invisible', visible: :visible)
end.to raise_error Capybara::ElementNotFound
expect do
@session.first(:css, 'a#invisible', visible: :visible, text: 'hidden link')
end.to raise_error Capybara::ElementNotFound
expect(@session.first(:css, 'a#visible', visible: :visible)).to be_truthy
end
it 'should default to Capybara.ignore_hidden_elements' do
Capybara.ignore_hidden_elements = true
expect do
@session.first(:css, 'a#invisible')
end.to raise_error Capybara::ElementNotFound
Capybara.ignore_hidden_elements = false
expect(@session.first(:css, 'a#invisible')).to be_truthy
expect(@session.first(:css, 'a')).to be_truthy
end
end
context 'within a scope' do
before do
@session.visit('/with_scope')
end
it 'should find the first element using the given locator' do
@session.within(:xpath, "//div[@id='for_bar']") do
expect(@session.first('.//form')).to be_truthy
end
end
end
context 'waiting behavior', requires: [:js] do
before do
@session.visit('/with_js')
end
it 'should not wait if minimum: 0' do
@session.click_link('clickable')
Capybara.using_wait_time(3) do
start_time = Time.now
expect(@session.first(:css, 'a#has-been-clicked', minimum: 0)).to be_nil
expect(Time.now - start_time).to be < 3
end
end
it 'should wait for at least one match by default' do
Capybara.using_wait_time(3) do
@session.click_link('clickable')
expect(@session.first(:css, 'a#has-been-clicked')).not_to be_nil
end
end
it 'should raise an error after waiting if no match' do
@session.click_link('clickable')
Capybara.using_wait_time(3) do
start_time = Time.now
expect do
@session.first(:css, 'a#not-a-real-link')
end.to raise_error Capybara::ElementNotFound
expect(Time.now - start_time).to be > 3
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/spec/session/response_code_spec.rb | lib/capybara/spec/session/response_code_spec.rb | # frozen_string_literal: true
Capybara::SpecHelper.spec '#status_code' do
it 'should return response codes', requires: [:status_code] do
@session.visit('/with_simple_html')
expect(@session.status_code).to eq(200)
end
end
| ruby | MIT | b3325b198464b806f07ec2011ceb532d6d5cf4ab | 2026-01-04T15:38:10.098638Z | false |
teamcapybara/capybara | https://github.com/teamcapybara/capybara/blob/b3325b198464b806f07ec2011ceb532d6d5cf4ab/lib/capybara/spec/session/reset_session_spec.rb | lib/capybara/spec/session/reset_session_spec.rb | # frozen_string_literal: true
Capybara::SpecHelper.spec '#reset_session!' do
it 'removes cookies from current domain' do
@session.visit('/set_cookie')
@session.visit('/get_cookie')
expect(@session).to have_content('test_cookie')
@session.reset_session!
@session.visit('/get_cookie')
expect(@session.body).not_to include('test_cookie')
end
it 'removes ALL cookies', requires: [:server] do
domains = ['localhost', '127.0.0.1']
domains.each do |domain|
@session.visit("http://#{domain}:#{@session.server.port}/set_cookie")
@session.visit("http://#{domain}:#{@session.server.port}/get_cookie")
expect(@session).to have_content('test_cookie')
end
@session.reset_session!
domains.each do |domain|
@session.visit("http://#{domain}:#{@session.server.port}/get_cookie")
expect(@session.body).not_to include('test_cookie')
end
end
it 'resets current url, host, path' do
@session.visit '/foo'
expect(@session.current_url).not_to be_empty
expect(@session.current_host).not_to be_empty
expect(@session.current_path).to eq('/foo')
@session.reset_session!
expect(@session.current_url).to satisfy('be a blank url') { |url| [nil, '', 'about:blank'].include? url }
expect(@session.current_path).to satisfy('be a blank path') { |path| ['', nil].include? path }
expect(@session.current_host).to be_nil
end
it 'resets page body' do
@session.visit('/with_html')
expect(@session).to have_content('This is a test')
expect(@session.find('.//h1').text).to include('This is a test')
@session.reset_session!
expect(@session.body).not_to include('This is a test')
expect(@session).to have_no_selector('.//h1')
end
it 'is synchronous' do
@session.visit('/with_slow_unload')
expect(@session).to have_selector(:css, 'div')
@session.reset_session!
expect(@session).to have_no_selector :xpath, '/html/body/*', wait: false
end
it 'handles modals during unload', requires: [:modals] do
@session.visit('/with_unload_alert')
expect(@session).to have_selector(:css, 'div')
expect { @session.reset_session! }.not_to raise_error
expect(@session).to have_no_selector :xpath, '/html/body/*', wait: false
end
it 'handles already open modals', requires: [:modals] do
@session.visit('/with_unload_alert')
@session.click_link('Go away')
expect { @session.reset_session! }.not_to raise_error
expect(@session).to have_no_selector :xpath, '/html/body/*', wait: false
end
it 'raises any standard errors caught inside the server', requires: [:server] do
quietly { @session.visit('/error') }
expect do
@session.reset_session!
end.to raise_error(TestApp::TestAppError)
@session.visit('/')
expect(@session.current_path).to eq('/')
end
it 'closes extra windows', requires: [:windows] do
@session.visit('/with_html')
@session.open_new_window
@session.open_new_window
expect(@session.windows.size).to eq 3
@session.reset_session!
expect(@session.windows.size).to eq 1
end
it 'closes extra windows when not on the first window', requires: [:windows] do
@session.visit('/with_html')
@session.switch_to_window(@session.open_new_window)
@session.open_new_window
expect(@session.windows.size).to eq 3
@session.reset_session!
expect(@session.windows.size).to eq 1
end
it 'does not block opening a new window after a frame was switched to and not switched back', requires: [:windows] do
@session.visit('/with_iframe?id=test_iframe&url=/')
@session.switch_to_frame(@session.find(:frame, 'test_iframe'))
within_window_test = lambda do
@session.within_window(@session.open_new_window) do
@session.visit('/')
end
end
expect(&within_window_test).to raise_error(Capybara::ScopeError)
@session.reset_session!
expect(&within_window_test).not_to raise_error
end
context 'When reuse_server == false' do
let!(:orig_reuse_server) { Capybara.reuse_server }
before do
Capybara.reuse_server = false
end
after do
Capybara.reuse_server = orig_reuse_server
end
it 'raises any standard errors caught inside the server during a second session', requires: [:server] do
Capybara.using_driver(@session.mode) do
Capybara.using_session(:another_session) do
another_session = Capybara.current_session
quietly { another_session.visit('/error') }
expect do
another_session.reset_session!
end.to raise_error(TestApp::TestAppError)
another_session.visit('/')
expect(another_session.current_path).to eq('/')
end
end
end
end
it 'raises configured errors caught inside the server', requires: [:server] do
prev_errors = Capybara.server_errors.dup
Capybara.server_errors = [LoadError]
quietly { @session.visit('/error') }
expect do
@session.reset_session!
end.not_to raise_error
quietly { @session.visit('/load_error') }
expect do
@session.reset_session!
end.to raise_error(LoadError)
Capybara.server_errors = prev_errors
end
it 'ignores server errors when `Capybara.raise_server_errors = false`', requires: [:server] do
Capybara.raise_server_errors = false
quietly { @session.visit('/error') }
@session.reset_session!
@session.visit('/')
expect(@session.current_path).to eq('/')
end
end
| ruby | MIT | b3325b198464b806f07ec2011ceb532d6d5cf4ab | 2026-01-04T15:38:10.098638Z | false |
teamcapybara/capybara | https://github.com/teamcapybara/capybara/blob/b3325b198464b806f07ec2011ceb532d6d5cf4ab/lib/capybara/spec/session/attach_file_spec.rb | lib/capybara/spec/session/attach_file_spec.rb | # frozen_string_literal: true
Capybara::SpecHelper.spec '#attach_file' do
let(:test_file_path) { File.expand_path('../fixtures/test_file.txt', File.dirname(__FILE__)) }
let(:another_test_file_path) { File.expand_path('../fixtures/another_test_file.txt', File.dirname(__FILE__)) }
let(:test_jpg_file_path) { File.expand_path('../fixtures/capybara.jpg', File.dirname(__FILE__)) }
let(:no_extension_file_path) { File.expand_path('../fixtures/no_extension', File.dirname(__FILE__)) }
before do
@session.visit('/form')
end
context 'with normal form' do
it 'should set a file path by id' do
@session.attach_file 'form_image', with_os_path_separators(__FILE__)
@session.click_button('awesome')
expect(extract_results(@session)['image']).to end_with(File.basename(__FILE__))
end
it 'should set a file path by label' do
@session.attach_file 'Image', with_os_path_separators(__FILE__)
@session.click_button('awesome')
expect(extract_results(@session)['image']).to end_with(File.basename(__FILE__))
end
it 'should be able to set on element if no locator passed' do
ff = @session.find(:file_field, 'Image')
ff.attach_file(with_os_path_separators(__FILE__))
@session.click_button('awesome')
expect(extract_results(@session)['image']).to end_with(File.basename(__FILE__))
end
it 'casts to string' do
@session.attach_file :form_image, with_os_path_separators(__FILE__)
@session.click_button('awesome')
expect(extract_results(@session)['image']).to end_with(File.basename(__FILE__))
end
end
context 'with multipart form' do
it 'should set a file path by id' do
@session.attach_file 'form_document', with_os_path_separators(test_file_path)
@session.click_button('Upload Single')
expect(@session).to have_content(File.read(test_file_path))
end
it 'should set a file path by label' do
@session.attach_file 'Single Document', with_os_path_separators(test_file_path)
@session.click_button('Upload Single')
expect(@session).to have_content(File.read(test_file_path))
end
it 'should not break if no file is submitted' do
@session.click_button('Upload Single')
expect(@session).to have_content('No file uploaded')
end
it 'should send prior hidden field if no file submitted' do
@session.click_button('Upload Empty With Hidden')
expect(extract_results(@session)['document2']).to eq('hidden_field')
expect(extract_content_type(@session)).to start_with('multipart/form-data;')
end
it 'should send content type text/plain when uploading a text file' do
@session.attach_file 'Single Document', with_os_path_separators(test_file_path)
@session.click_button 'Upload Single'
expect(@session).to have_content('text/plain')
end
it 'should send content type image/jpeg when uploading an image' do
@session.attach_file 'Single Document', with_os_path_separators(test_jpg_file_path)
@session.click_button 'Upload Single'
expect(@session).to have_content('image/jpeg')
end
it 'should not break when uploading a file without extension' do
@session.attach_file 'Single Document', with_os_path_separators(no_extension_file_path)
@session.click_button 'Upload Single'
expect(@session).to have_content(File.read(no_extension_file_path))
end
it 'should not break when using HTML5 multiple file input' do
@session.attach_file 'Multiple Documents', with_os_path_separators(test_file_path)
@session.click_button('Upload Multiple')
expect(@session).to have_content(File.read(test_file_path))
expect(@session.body).to include('1 | ') # number of files
end
it 'should not break when using HTML5 multiple file input uploading multiple files' do
@session.attach_file('Multiple Documents',
[test_file_path, another_test_file_path].map { |f| with_os_path_separators(f) })
@session.click_button('Upload Multiple')
expect(@session).to have_content('2 | ') # number of files
expect(@session.body).to include(File.read(test_file_path))
expect(@session.body).to include(File.read(another_test_file_path))
end
it 'should not send anything when attaching no files to a multiple upload field' do
@session.click_button('Upload Empty Multiple')
expect(@session).to have_content('Successfully ignored empty file field')
end
it 'should not append files to already attached' do
@session.attach_file 'Multiple Documents', with_os_path_separators(test_file_path)
@session.attach_file 'Multiple Documents', with_os_path_separators(another_test_file_path)
@session.click_button('Upload Multiple')
expect(@session).to have_content('1 | ') # number of files
expect(@session.body).to include(File.read(another_test_file_path))
expect(@session.body).not_to include(File.read(test_file_path))
end
it 'should fire change once when uploading multiple files from empty', requires: [:js] do
@session.visit('with_js')
@session.attach_file('multiple-file',
[test_file_path, another_test_file_path].map { |f| with_os_path_separators(f) })
expect(@session).to have_css('.file_change', count: 1)
end
it 'should fire change once for each set of files uploaded', requires: [:js] do
@session.visit('with_js')
@session.attach_file('multiple-file', [test_jpg_file_path].map { |f| with_os_path_separators(f) })
@session.attach_file('multiple-file',
[test_file_path, another_test_file_path].map { |f| with_os_path_separators(f) })
expect(@session).to have_css('.file_change', count: 2)
end
end
context "with a locator that doesn't exist" do
it 'should raise an error' do
msg = /Unable to find file field "does not exist"/
expect do
@session.attach_file('does not exist', with_os_path_separators(test_file_path))
end.to raise_error(Capybara::ElementNotFound, msg)
end
end
context "with a path that doesn't exist" do
it 'should raise an error' do
expect { @session.attach_file('Image', '/no_such_file.png') }.to raise_error(Capybara::FileNotFound)
end
end
context 'with :exact option' do
it 'should set a file path by partial label when false' do
@session.attach_file 'Imag', with_os_path_separators(__FILE__), exact: false
@session.click_button('awesome')
expect(extract_results(@session)['image']).to end_with(File.basename(__FILE__))
end
it 'should not allow partial matches when true' do
expect do
@session.attach_file 'Imag', with_os_path_separators(__FILE__), exact: true
end.to raise_error(Capybara::ElementNotFound)
end
end
context 'with :make_visible option', requires: %i[js es_args] do
it 'applies a default style change when true' do
@session.visit('/with_js')
expect do
@session.attach_file('hidden_file', with_os_path_separators(__FILE__))
end.to raise_error Capybara::ElementNotFound
expect do
@session.attach_file('hidden_file', with_os_path_separators(__FILE__), make_visible: true)
end.not_to raise_error
end
it 'accepts a hash of styles to be applied' do
@session.visit('/with_js')
expect do
@session.attach_file('hidden_file',
with_os_path_separators(__FILE__),
make_visible: { opacity: 1, display: 'block' })
end.not_to raise_error
end
it 'raises an error when the file input is not made visible' do
@session.visit('/with_js')
expect do
@session.attach_file('hidden_file', with_os_path_separators(__FILE__), make_visible: { color: 'red' })
end.to raise_error(Capybara::ExpectationNotMet)
end
it 'resets the style when done' do
@session.visit('/with_js')
@session.attach_file('hidden_file', with_os_path_separators(__FILE__), make_visible: true)
expect(@session.evaluate_script('arguments[0].style.display', @session.find(:css, '#hidden_file', visible: :all))).to eq 'none'
end
it 'should fire change' do
@session.visit('/with_js')
@session.attach_file('hidden_file', with_os_path_separators(__FILE__), make_visible: true)
expect(@session).to have_css('.file_change')
end
end
context 'with a block', requires: %i[js] do
it 'can upload by clicking the file input' do
@session.attach_file(with_os_path_separators(__FILE__)) do
@session.find(:file_field, 'form[image]').click
end
@session.click_button('awesome')
expect(extract_results(@session)['image']).to end_with(File.basename(__FILE__))
end
it 'can upload by clicking the label' do
@session.attach_file(with_os_path_separators(__FILE__)) do
@session.find(:label, 'Hidden Image').click
end
@session.click_button('awesome')
expect(extract_results(@session)['hidden_image']).to end_with(File.basename(__FILE__))
end
it 'should fire change' do
@session.visit('/with_js')
@session.attach_file(with_os_path_separators(__FILE__)) do
@session.find(:label, 'Label for hidden file input').click
end
expect(@session).to have_css('.file_change')
end
end
end
| ruby | MIT | b3325b198464b806f07ec2011ceb532d6d5cf4ab | 2026-01-04T15:38:10.098638Z | false |
teamcapybara/capybara | https://github.com/teamcapybara/capybara/blob/b3325b198464b806f07ec2011ceb532d6d5cf4ab/lib/capybara/spec/session/assert_all_of_selectors_spec.rb | lib/capybara/spec/session/assert_all_of_selectors_spec.rb | # frozen_string_literal: true
Capybara::SpecHelper.spec '#assert_all_of_selectors' do
before do
@session.visit('/with_html')
end
it 'should be true if the given selectors are on the page' do
@session.assert_all_of_selectors(:css, 'p a#foo', 'h2#h2one', 'h2#h2two')
end
it 'should be false if any of the given selectors are not on the page' do
expect { @session.assert_all_of_selectors(:css, 'p a#foo', 'h2#h2three', 'h2#h2one') }.to raise_error(Capybara::ElementNotFound)
end
it 'should use default selector' do
Capybara.default_selector = :css
expect { @session.assert_all_of_selectors('p a#foo', 'h2#h2three', 'h2#h2one') }.to raise_error(Capybara::ElementNotFound)
@session.assert_all_of_selectors('p a#foo', 'h2#h2two', 'h2#h2one')
end
it 'should support filter block' do
expect { @session.assert_all_of_selectors(:css, 'h2#h2one', 'h2#h2two') { |n| n[:id] == 'h2one' } }.to raise_error(Capybara::ElementNotFound, /custom filter block/)
end
context 'should respect scopes' do
it 'when used with `within`' do
@session.within "//p[@id='first']" do
@session.assert_all_of_selectors(".//a[@id='foo']")
expect { @session.assert_all_of_selectors(".//a[@id='red']") }.to raise_error(Capybara::ElementNotFound)
end
end
it 'when called on elements' do
el = @session.find "//p[@id='first']"
el.assert_all_of_selectors(".//a[@id='foo']")
expect { el.assert_all_of_selectors(".//a[@id='red']") }.to raise_error(Capybara::ElementNotFound)
end
end
context 'with options' do
it 'should apply options to all locators' do
@session.assert_all_of_selectors(:field, 'normal', 'additional_newline', type: :textarea)
expect { @session.assert_all_of_selectors(:field, 'normal', 'test_field', 'additional_newline', type: :textarea) }.to raise_error(Capybara::ElementNotFound)
end
end
context 'with wait', requires: [:js] do
it 'should not raise error if all the elements appear before given wait duration' do
Capybara.using_wait_time(0.1) do
@session.visit('/with_js')
@session.click_link('Click me')
@session.assert_all_of_selectors(:css, 'a#clickable', 'a#has-been-clicked', '#drag', wait: 1.5)
end
end
end
end
Capybara::SpecHelper.spec '#assert_none_of_selectors' do
before do
@session.visit('/with_html')
end
it 'should be false if any of the given locators are on the page' do
expect { @session.assert_none_of_selectors(:xpath, '//p', '//a') }.to raise_error(Capybara::ElementNotFound)
expect { @session.assert_none_of_selectors(:xpath, '//abbr', '//a') }.to raise_error(Capybara::ElementNotFound)
expect { @session.assert_none_of_selectors(:css, 'p a#foo') }.to raise_error(Capybara::ElementNotFound)
end
it 'should be true if none of the given locators are on the page' do
@session.assert_none_of_selectors(:xpath, '//abbr', '//td')
@session.assert_none_of_selectors(:css, 'p a#doesnotexist', 'abbr')
end
it 'should use default selector' do
Capybara.default_selector = :css
@session.assert_none_of_selectors('p a#doesnotexist', 'abbr')
expect { @session.assert_none_of_selectors('abbr', 'p a#foo') }.to raise_error(Capybara::ElementNotFound)
end
context 'should respect scopes' do
it 'when used with `within`' do
@session.within "//p[@id='first']" do
expect { @session.assert_none_of_selectors(".//a[@id='foo']") }.to raise_error(Capybara::ElementNotFound)
@session.assert_none_of_selectors(".//a[@id='red']")
end
end
it 'when called on an element' do
el = @session.find "//p[@id='first']"
expect { el.assert_none_of_selectors(".//a[@id='foo']") }.to raise_error(Capybara::ElementNotFound)
el.assert_none_of_selectors(".//a[@id='red']")
end
end
context 'with options' do
it 'should apply the options to all locators' do
expect { @session.assert_none_of_selectors('//p//a', text: 'Redirect') }.to raise_error(Capybara::ElementNotFound)
@session.assert_none_of_selectors('//p', text: 'Doesnotexist')
end
it 'should discard all matches where the given regexp is matched' do
expect { @session.assert_none_of_selectors('//p//a', text: /re[dab]i/i, count: 1) }.to raise_error(Capybara::ElementNotFound)
@session.assert_none_of_selectors('//p//a', text: /Red$/)
end
end
context 'with wait', requires: [:js] do
it 'should not find elements if they appear after given wait duration' do
@session.visit('/with_js')
@session.click_link('Click me')
@session.assert_none_of_selectors(:css, '#new_field', 'a#has-been-clicked', wait: 0.1)
end
end
end
Capybara::SpecHelper.spec '#assert_any_of_selectors' do
before do
@session.visit('/with_html')
end
it 'should be true if any of the given selectors are on the page' do
@session.assert_any_of_selectors(:css, 'a#foo', 'h2#h2three')
@session.assert_any_of_selectors(:css, 'h2#h2three', 'a#foo')
end
it 'should be false if none of the given selectors are on the page' do
expect { @session.assert_any_of_selectors(:css, 'h2#h2three', 'h4#h4four') }.to raise_error(Capybara::ElementNotFound)
end
it 'should use default selector' do
Capybara.default_selector = :css
expect { @session.assert_any_of_selectors('h2#h2three', 'h5#h5five') }.to raise_error(Capybara::ElementNotFound)
@session.assert_any_of_selectors('p a#foo', 'h2#h2two', 'h2#h2one')
end
it 'should support filter block' do
expect { @session.assert_any_of_selectors(:css, 'h2#h2one', 'h2#h2two') { |_n| false } }.to raise_error(Capybara::ElementNotFound, /custom filter block/)
end
end
| ruby | MIT | b3325b198464b806f07ec2011ceb532d6d5cf4ab | 2026-01-04T15:38:10.098638Z | false |
teamcapybara/capybara | https://github.com/teamcapybara/capybara/blob/b3325b198464b806f07ec2011ceb532d6d5cf4ab/lib/capybara/spec/session/has_selector_spec.rb | lib/capybara/spec/session/has_selector_spec.rb | # frozen_string_literal: true
Capybara::SpecHelper.spec '#has_selector?' do
before do
@session.visit('/with_html')
end
it 'should be true if the given selector is on the page' do
expect(@session).to have_selector(:xpath, '//p')
expect(@session).to have_selector(:css, 'p a#foo')
expect(@session).to have_selector("//p[contains(.,'est')]")
end
it 'should be false if the given selector is not on the page' do
expect(@session).not_to have_selector(:xpath, '//abbr')
expect(@session).not_to have_selector(:css, 'p a#doesnotexist')
expect(@session).not_to have_selector("//p[contains(.,'thisstringisnotonpage')]")
end
it 'should use default selector' do
Capybara.default_selector = :css
expect(@session).not_to have_selector('p a#doesnotexist')
expect(@session).to have_selector('p a#foo')
end
it 'should respect scopes' do
@session.within "//p[@id='first']" do
expect(@session).to have_selector(".//a[@id='foo']")
expect(@session).not_to have_selector(".//a[@id='red']")
end
end
it 'should accept a filter block' do
expect(@session).to have_selector(:css, 'a', count: 1) { |el| el[:id] == 'foo' }
end
context 'with count' do
it 'should be true if the content is on the page the given number of times' do
expect(@session).to have_selector('//p', count: 3)
expect(@session).to have_selector("//p//a[@id='foo']", count: 1)
expect(@session).to have_selector("//p[contains(.,'est')]", count: 1)
end
it 'should be false if the content is on the page the given number of times' do
expect(@session).not_to have_selector('//p', count: 6)
expect(@session).not_to have_selector("//p//a[@id='foo']", count: 2)
expect(@session).not_to have_selector("//p[contains(.,'est')]", count: 5)
end
it "should be false if the content isn't on the page at all" do
expect(@session).not_to have_selector('//abbr', count: 2)
expect(@session).not_to have_selector("//p//a[@id='doesnotexist']", count: 1)
end
end
context 'with text' do
it 'should discard all matches where the given string is not contained' do
expect(@session).to have_selector('//p//a', text: 'Redirect', count: 1)
expect(@session).to have_selector(:css, 'p a', text: 'Redirect', count: 1)
expect(@session).not_to have_selector('//p', text: 'Doesnotexist')
end
it 'should respect visibility setting' do
expect(@session).to have_selector(:id, 'hidden-text', text: 'Some of this text is hidden!', visible: :all)
expect(@session).not_to have_selector(:id, 'hidden-text', text: 'Some of this text is hidden!', visible: :visible)
Capybara.ignore_hidden_elements = false
expect(@session).to have_selector(:id, 'hidden-text', text: 'Some of this text is hidden!', visible: :all)
Capybara.visible_text_only = true
expect(@session).not_to have_selector(:id, 'hidden-text', text: 'Some of this text is hidden!', visible: :visible)
end
it 'should discard all matches where the given regexp is not matched' do
expect(@session).to have_selector('//p//a', text: /re[dab]i/i, count: 1)
expect(@session).not_to have_selector('//p//a', text: /Red$/)
end
it 'should raise when extra parameters passed' do
expect do
expect(@session).to have_selector(:css, 'p a#foo', 'extra')
end.to raise_error ArgumentError, /extra/
end
context 'with whitespace normalization' do
context 'Capybara.default_normalize_ws = false' do
it 'should support normalize_ws option' do
Capybara.default_normalize_ws = false
expect(@session).not_to have_selector(:id, 'second', text: 'text with whitespace')
expect(@session).to have_selector(:id, 'second', text: 'text with whitespace', normalize_ws: true)
end
end
context 'Capybara.default_normalize_ws = true' do
it 'should support normalize_ws option' do
Capybara.default_normalize_ws = true
expect(@session).to have_selector(:id, 'second', text: 'text with whitespace')
expect(@session).not_to have_selector(:id, 'second', text: 'text with whitespace', normalize_ws: false)
end
end
end
end
context 'with exact_text' do
context 'string' do
it 'should only match elements that match exactly' do
expect(@session).to have_selector(:id, 'h2one', exact_text: 'Header Class Test One')
expect(@session).to have_no_selector(:id, 'h2one', exact_text: 'Header Class Test')
end
end
context 'boolean' do
it 'should only match elements that match exactly when true' do
expect(@session).to have_selector(:id, 'h2one', text: 'Header Class Test One', exact_text: true)
expect(@session).to have_no_selector(:id, 'h2one', text: 'Header Class Test', exact_text: true)
end
it 'should match substrings when false' do
expect(@session).to have_selector(:id, 'h2one', text: 'Header Class Test One', exact_text: false)
expect(@session).to have_selector(:id, 'h2one', text: 'Header Class Test', exact_text: false)
end
it 'should warn if text option is a regexp that it is ignoring exact_text' do
allow(Capybara::Helpers).to receive(:warn)
expect(@session).to have_selector(:id, 'h2one', text: /Class Test/, exact_text: true)
expect(Capybara::Helpers).to have_received(:warn).with(/'exact_text' option is not supported/)
end
end
context 'regexp' do
it 'should only match when it fully matches' do
expect(@session).to have_selector(:id, 'h2one', exact_text: /Header Class Test One/)
expect(@session).to have_no_selector(:id, 'h2one', exact_text: /Header Class Test/)
expect(@session).to have_no_selector(:id, 'h2one', exact_text: /Class Test One/)
expect(@session).to have_no_selector(:id, 'h2one', exact_text: /Class Test/)
end
end
end
context 'datalist' do
it 'should match options' do
@session.visit('/form')
expect(@session).to have_selector(:datalist_input, with_options: %w[Jaguar Audi Mercedes])
expect(@session).not_to have_selector(:datalist_input, with_options: %w[Ford Chevy])
end
end
end
Capybara::SpecHelper.spec '#has_no_selector?' do
before do
@session.visit('/with_html')
end
it 'should be false if the given selector is on the page' do
expect(@session).not_to have_no_selector(:xpath, '//p')
expect(@session).not_to have_no_selector(:css, 'p a#foo')
expect(@session).not_to have_no_selector("//p[contains(.,'est')]")
end
it 'should be true if the given selector is not on the page' do
expect(@session).to have_no_selector(:xpath, '//abbr')
expect(@session).to have_no_selector(:css, 'p a#doesnotexist')
expect(@session).to have_no_selector("//p[contains(.,'thisstringisnotonpage')]")
end
it 'should use default selector' do
Capybara.default_selector = :css
expect(@session).to have_no_selector('p a#doesnotexist')
expect(@session).not_to have_no_selector('p a#foo')
end
it 'should respect scopes' do
@session.within "//p[@id='first']" do
expect(@session).not_to have_no_selector(".//a[@id='foo']")
expect(@session).to have_no_selector(".//a[@id='red']")
end
end
it 'should accept a filter block' do
expect(@session).to have_no_selector(:css, 'a#foo') { |el| el[:id] != 'foo' }
end
context 'with count' do
it 'should be false if the content is on the page the given number of times' do
expect(@session).not_to have_no_selector('//p', count: 3)
expect(@session).not_to have_no_selector("//p//a[@id='foo']", count: 1)
expect(@session).not_to have_no_selector("//p[contains(.,'est')]", count: 1)
end
it 'should be true if the content is on the page the wrong number of times' do
expect(@session).to have_no_selector('//p', count: 6)
expect(@session).to have_no_selector("//p//a[@id='foo']", count: 2)
expect(@session).to have_no_selector("//p[contains(.,'est')]", count: 5)
end
it "should be true if the content isn't on the page at all" do
expect(@session).to have_no_selector('//abbr', count: 2)
expect(@session).to have_no_selector("//p//a[@id='doesnotexist']", count: 1)
end
end
context 'with text' do
it 'should discard all matches where the given string is contained' do
expect(@session).not_to have_no_selector('//p//a', text: 'Redirect', count: 1)
expect(@session).to have_no_selector('//p', text: 'Doesnotexist')
end
it 'should discard all matches where the given regexp is matched' do
expect(@session).not_to have_no_selector('//p//a', text: /re[dab]i/i, count: 1)
expect(@session).to have_no_selector('//p//a', text: /Red$/)
end
it 'should error when matching element exists' do
expect do
expect(@session).to have_no_selector('//h2', text: 'Header Class Test Five')
end.to raise_error RSpec::Expectations::ExpectationNotMetError
end
end
end
| ruby | MIT | b3325b198464b806f07ec2011ceb532d6d5cf4ab | 2026-01-04T15:38:10.098638Z | false |
teamcapybara/capybara | https://github.com/teamcapybara/capybara/blob/b3325b198464b806f07ec2011ceb532d6d5cf4ab/lib/capybara/spec/session/has_button_spec.rb | lib/capybara/spec/session/has_button_spec.rb | # frozen_string_literal: true
Capybara::SpecHelper.spec '#has_button?' do
before do
@session.visit('/form')
end
it 'should be true if the given button is on the page' do
expect(@session).to have_button('med')
expect(@session).to have_button('crap321')
expect(@session).to have_button(:crap321)
expect(@session).to have_button('button with label element')
expect(@session).to have_button('button within label element')
end
it 'should be true for disabled buttons if disabled: true' do
expect(@session).to have_button('Disabled button', disabled: true)
end
it 'should be false if the given button is not on the page' do
expect(@session).not_to have_button('monkey')
end
it 'should be false for disabled buttons by default' do
expect(@session).not_to have_button('Disabled button')
end
it 'should be false for disabled buttons if disabled: false' do
expect(@session).not_to have_button('Disabled button', disabled: false)
end
it 'should be true for disabled buttons if disabled: :all' do
expect(@session).to have_button('Disabled button', disabled: :all)
end
it 'should be true for enabled buttons if disabled: :all' do
expect(@session).to have_button('med', disabled: :all)
end
it 'should be true for exact match if exact: true' do
expect(@session).to have_button('med', exact: true)
end
it 'can verify button type' do
expect(@session).to have_button('awe123', type: 'submit')
expect(@session).not_to have_button('awe123', type: 'reset')
end
it 'should be true for role=button when enable_aria_role: true' do
expect(@session).to have_button('ARIA button', enable_aria_role: true)
end
it 'should be false for a role=button within a label when enable_aria_role: true' do
expect(@session).not_to have_button('role=button within label', enable_aria_role: true)
end
it 'should be false for role=button when enable_aria_role: false' do
expect(@session).not_to have_button('ARIA button', enable_aria_role: false)
end
it 'should be false for a role=button within a label when enable_aria_role: false' do
expect(@session).not_to have_button('role=button within label', enable_aria_role: false)
end
it 'should not affect other selectors when enable_aria_role: true' do
expect(@session).to have_button('Click me!', enable_aria_role: true)
end
it 'should not affect other selectors when enable_aria_role: false' do
expect(@session).to have_button('Click me!', enable_aria_role: false)
end
context 'with focused:', requires: [:active_element] do
it 'should be true if a field has focus when focused: true' do
@session.send_keys(:tab)
expect(@session).to have_button('A Button', focused: true)
end
it 'should be true if a field does not have focus when focused: false' do
expect(@session).to have_button('A Button', focused: false)
end
end
it 'should raise an error if an invalid option is passed' do
expect do
expect(@session).to have_button('A Button', invalid: true)
end.to raise_error(ArgumentError, 'Invalid option(s) :invalid, should be one of :above, :below, :left_of, :right_of, :near, :count, :minimum, :maximum, :between, :text, :id, :class, :style, :visible, :obscured, :exact, :exact_text, :normalize_ws, :match, :wait, :filter_set, :focused, :disabled, :name, :value, :title, :type')
end
end
Capybara::SpecHelper.spec '#has_no_button?' do
before do
@session.visit('/form')
end
it 'should be true if the given button is on the page' do
expect(@session).not_to have_no_button('med')
expect(@session).not_to have_no_button('crap321')
end
it 'should be true for disabled buttons if disabled: true' do
expect(@session).not_to have_no_button('Disabled button', disabled: true)
end
it 'should be false if the given button is not on the page' do
expect(@session).to have_no_button('monkey')
end
it 'should be false for disabled buttons by default' do
expect(@session).to have_no_button('Disabled button')
end
it 'should be false for disabled buttons if disabled: false' do
expect(@session).to have_no_button('Disabled button', disabled: false)
end
it 'should be true for no exact match if exact: true' do
expect(@session).to have_no_button('button', exact: true)
end
it 'should be true for role=button when enable_aria_role: false' do
expect(@session).to have_no_button('ARIA button', enable_aria_role: false)
end
it 'should be true for role=button within a label when enable_aria_role: false' do
expect(@session).to have_no_button('role=button within label', enable_aria_role: false)
end
it 'should be false for role=button when enable_aria_role: true' do
expect(@session).not_to have_no_button('ARIA button', enable_aria_role: true)
end
it 'should be true for a role=button within a label when enable_aria_role: true' do
# label element does not associate with aria button
expect(@session).to have_no_button('role=button within label', enable_aria_role: true)
end
it 'should not affect other selectors when enable_aria_role: true' do
expect(@session).to have_no_button('Junk button that does not exist', enable_aria_role: true)
end
it 'should not affect other selectors when enable_aria_role: false' do
expect(@session).to have_no_button('Junk button that does not exist', enable_aria_role: false)
end
context 'with focused:', requires: [:active_element] do
it 'should be true if a button does not have focus when focused: true' do
expect(@session).to have_no_button('A Button', focused: true)
end
it 'should be false if a button has focus when focused: false' do
@session.send_keys(:tab)
expect(@session).to have_no_button('A Button', focused: 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/spec/session/accept_confirm_spec.rb | lib/capybara/spec/session/accept_confirm_spec.rb | # frozen_string_literal: true
Capybara::SpecHelper.spec '#accept_confirm', requires: [:modals] do
before do
@session.visit('/with_js')
end
it 'should accept the confirm' do
@session.accept_confirm do
@session.click_link('Open confirm')
end
expect(@session).to have_xpath("//a[@id='open-confirm' and @confirmed='true']")
end
it 'should return the message presented' do
message = @session.accept_confirm do
@session.click_link('Open confirm')
end
expect(message).to eq('Confirm opened')
end
it 'should work with nested modals' do
expect do
@session.dismiss_confirm 'Are you really sure?' do
@session.accept_confirm 'Are you sure?' do
@session.click_link('Open check twice')
end
end
end.not_to raise_error
expect(@session).to have_xpath("//a[@id='open-twice' and @confirmed='false']")
end
end
| ruby | MIT | b3325b198464b806f07ec2011ceb532d6d5cf4ab | 2026-01-04T15:38:10.098638Z | false |
teamcapybara/capybara | https://github.com/teamcapybara/capybara/blob/b3325b198464b806f07ec2011ceb532d6d5cf4ab/lib/capybara/spec/session/has_xpath_spec.rb | lib/capybara/spec/session/has_xpath_spec.rb | # frozen_string_literal: true
Capybara::SpecHelper.spec '#has_xpath?' do
before do
@session.visit('/with_html')
end
it 'should be true if the given selector is on the page' do
expect(@session).to have_xpath('//p')
expect(@session).to have_xpath("//p//a[@id='foo']")
expect(@session).to have_xpath("//p[contains(.,'est')]")
end
it 'should support :id option' do
expect(@session).to have_xpath('//h2', id: 'h2one')
expect(@session).to have_xpath('//h2')
expect(@session).to have_xpath('//h2', id: /h2o/)
end
it 'should support :class option' do
expect(@session).to have_xpath('//li', class: 'guitarist')
expect(@session).to have_xpath('//li', class: /guitar/)
expect(@session).to have_xpath('//li', class: /guitar|drummer/)
expect(@session).to have_xpath('//li', class: %w[beatle guitarist])
expect(@session).to have_xpath('//li', class: /.*/)
end
it 'should be false if the given selector is not on the page' do
expect(@session).not_to have_xpath('//abbr')
expect(@session).not_to have_xpath("//p//a[@id='doesnotexist']")
expect(@session).not_to have_xpath("//p[contains(.,'thisstringisnotonpage')]")
end
it 'should use xpath even if default selector is CSS' do
Capybara.default_selector = :css
expect(@session).not_to have_xpath("//p//a[@id='doesnotexist']")
end
it 'should respect scopes' do
@session.within "//p[@id='first']" do
expect(@session).to have_xpath(".//a[@id='foo']")
expect(@session).not_to have_xpath(".//a[@id='red']")
end
end
it 'should wait for content to appear', requires: [:js] do
Capybara.using_wait_time(3) do
@session.visit('/with_js')
@session.click_link('Click me') # updates page after 500ms
expect(@session).to have_xpath("//input[@type='submit' and @value='New Here']")
end
end
context 'with count' do
it 'should be true if the content occurs the given number of times' do
expect(@session).to have_xpath('//p', count: 3)
expect(@session).to have_xpath("//p//a[@id='foo']", count: 1)
expect(@session).to have_xpath("//p[contains(.,'est')]", count: 1)
expect(@session).to have_xpath("//p//a[@id='doesnotexist']", count: 0)
expect(@session).to have_xpath('//li', class: /guitar|drummer/, count: 4)
expect(@session).to have_xpath('//li', id: /john|paul/, class: /guitar|drummer/, count: 2)
expect(@session).to have_xpath('//li', class: %w[beatle guitarist], count: 2)
end
it 'should be false if the content occurs a different number of times than the given' do
expect(@session).not_to have_xpath('//p', count: 6)
expect(@session).not_to have_xpath("//p//a[@id='foo']", count: 2)
expect(@session).not_to have_xpath("//p[contains(.,'est')]", count: 5)
expect(@session).not_to have_xpath("//p//a[@id='doesnotexist']", count: 1)
end
end
context 'with text' do
it 'should discard all matches where the given string is not contained' do
expect(@session).to have_xpath('//p//a', text: 'Redirect', count: 1)
expect(@session).not_to have_xpath('//p', text: 'Doesnotexist')
end
it 'should discard all matches where the given regexp is not matched' do
expect(@session).to have_xpath('//p//a', text: /re[dab]i/i, count: 1)
expect(@session).not_to have_xpath('//p//a', text: /Red$/)
end
end
end
Capybara::SpecHelper.spec '#has_no_xpath?' do
before do
@session.visit('/with_html')
end
it 'should be false if the given selector is on the page' do
expect(@session).not_to have_no_xpath('//p')
expect(@session).not_to have_no_xpath("//p//a[@id='foo']")
expect(@session).not_to have_no_xpath("//p[contains(.,'est')]")
end
it 'should be true if the given selector is not on the page' do
expect(@session).to have_no_xpath('//abbr')
expect(@session).to have_no_xpath("//p//a[@id='doesnotexist']")
expect(@session).to have_no_xpath("//p[contains(.,'thisstringisnotonpage')]")
end
it 'should use xpath even if default selector is CSS' do
Capybara.default_selector = :css
expect(@session).to have_no_xpath("//p//a[@id='doesnotexist']")
end
it 'should respect scopes' do
@session.within "//p[@id='first']" do
expect(@session).not_to have_no_xpath(".//a[@id='foo']")
expect(@session).to have_no_xpath(".//a[@id='red']")
end
end
it 'should wait for content to disappear', requires: [:js] do
Capybara.default_max_wait_time = 2
@session.visit('/with_js')
@session.click_link('Click me')
expect(@session).to have_no_xpath("//p[@id='change']")
end
context 'with count' do
it 'should be false if the content occurs the given number of times' do
expect(@session).not_to have_no_xpath('//p', count: 3)
expect(@session).not_to have_no_xpath("//p//a[@id='foo']", count: 1)
expect(@session).not_to have_no_xpath("//p[contains(.,'est')]", count: 1)
expect(@session).not_to have_no_xpath("//p//a[@id='doesnotexist']", count: 0)
end
it 'should be true if the content occurs a different number of times than the given' do
expect(@session).to have_no_xpath('//p', count: 6)
expect(@session).to have_no_xpath("//p//a[@id='foo']", count: 2)
expect(@session).to have_no_xpath("//p[contains(.,'est')]", count: 5)
expect(@session).to have_no_xpath("//p//a[@id='doesnotexist']", count: 1)
end
end
context 'with text' do
it 'should discard all matches where the given string is contained' do
expect(@session).not_to have_no_xpath('//p//a', text: 'Redirect', count: 1)
expect(@session).to have_no_xpath('//p', text: 'Doesnotexist')
end
it 'should discard all matches where the given regexp is matched' do
expect(@session).not_to have_no_xpath('//p//a', text: /re[dab]i/i, count: 1)
expect(@session).to have_no_xpath('//p//a', text: /Red$/)
end
end
end
| ruby | MIT | b3325b198464b806f07ec2011ceb532d6d5cf4ab | 2026-01-04T15:38:10.098638Z | false |
teamcapybara/capybara | https://github.com/teamcapybara/capybara/blob/b3325b198464b806f07ec2011ceb532d6d5cf4ab/lib/capybara/spec/session/dismiss_confirm_spec.rb | lib/capybara/spec/session/dismiss_confirm_spec.rb | # frozen_string_literal: true
Capybara::SpecHelper.spec '#dismiss_confirm', requires: [:modals] do
before do
@session.visit('/with_js')
end
it 'should dismiss the confirm' do
@session.dismiss_confirm do
@session.click_link('Open confirm')
end
expect(@session).to have_xpath("//a[@id='open-confirm' and @confirmed='false']")
end
it 'should dismiss the confirm if the message matches' do
@session.dismiss_confirm 'Confirm opened' do
@session.click_link('Open confirm')
end
expect(@session).to have_xpath("//a[@id='open-confirm' and @confirmed='false']")
end
it "should not dismiss the confirm if the message doesn't match" do
expect do
@session.dismiss_confirm 'Incorrect Text' do
@session.click_link('Open confirm')
end
end.to raise_error(Capybara::ModalNotFound)
end
it 'should return the message presented' do
message = @session.dismiss_confirm do
@session.click_link('Open confirm')
end
expect(message).to eq('Confirm opened')
end
end
| ruby | MIT | b3325b198464b806f07ec2011ceb532d6d5cf4ab | 2026-01-04T15:38:10.098638Z | false |
teamcapybara/capybara | https://github.com/teamcapybara/capybara/blob/b3325b198464b806f07ec2011ceb532d6d5cf4ab/lib/capybara/spec/session/all_spec.rb | lib/capybara/spec/session/all_spec.rb | # frozen_string_literal: true
Capybara::SpecHelper.spec '#all' do
before do
@session.visit('/with_html')
end
it 'should find all elements using the given locator' do
expect(@session.all('//p').size).to eq(3)
expect(@session.all('//h1').first.text).to eq('This is a test')
expect(@session.all("//input[@id='test_field']").first.value).to eq('monkey')
end
it 'should return an empty array when nothing was found' do
expect(@session.all('//div[@id="nosuchthing"]')).to be_empty
end
it 'should wait for matching elements to appear', requires: [:js] do
Capybara.default_max_wait_time = 2
@session.visit('/with_js')
@session.click_link('Click me')
expect(@session.all(:css, 'a#has-been-clicked')).not_to be_empty
end
it 'should not wait if `minimum: 0` option is specified', requires: [:js] do
@session.visit('/with_js')
@session.click_link('Click me')
expect(@session.all(:css, 'a#has-been-clicked', minimum: 0)).to be_empty
end
it 'should accept an XPath instance', :exact_false do
@session.visit('/form')
@xpath = Capybara::Selector.new(:fillable_field, config: {}, format: :xpath).call('Name')
expect(@xpath).to be_a(XPath::Union)
@result = @session.all(@xpath).map(&:value)
expect(@result).to include('Smith', 'John', 'John Smith')
end
it 'should allow reversing the order' do
@session.visit('/form')
fields = @session.all(:fillable_field, 'Name', exact: false).to_a
reverse_fields = @session.all(:fillable_field, 'Name', order: :reverse, exact: false).to_a
expect(fields).to eq(reverse_fields.reverse)
end
it 'should raise an error when given invalid options' do
expect { @session.all('//p', schmoo: 'foo') }.to raise_error(ArgumentError)
end
it 'should not reload by default', requires: [:driver] do
paras = @session.all(:css, 'p', minimum: 3)
expect { paras[0].text }.not_to raise_error
@session.refresh
expect { paras[0].text }.to raise_error do |err|
expect(err).to be_an_invalid_element_error(@session)
end
end
context 'with allow_reload' do
it 'should reload if true' do
paras = @session.all(:css, 'p', allow_reload: true, minimum: 3)
expect { paras[0].text }.not_to raise_error
@session.refresh
sleep 1 # Ensure page has started to reload
expect(paras[0]).to have_text('Lorem ipsum dolor')
expect(paras[1]).to have_text('Duis aute irure dolor')
end
it 'should not reload if false', requires: [:driver] do
paras = @session.all(:css, 'p', allow_reload: false, minimum: 3)
expect { paras[0].text }.not_to raise_error
@session.refresh
sleep 1 # Ensure page has started to reload
expect { paras[0].text }.to raise_error do |err|
expect(err).to be_an_invalid_element_error(@session)
end
expect { paras[2].text }.to raise_error do |err|
expect(err).to be_an_invalid_element_error(@session)
end
end
end
context 'with css selectors' do
it 'should find all elements using the given selector' do
expect(@session.all(:css, 'h1').first.text).to eq('This is a test')
expect(@session.all(:css, "input[id='test_field']").first.value).to eq('monkey')
end
it 'should find all elements when given a list of selectors' do
expect(@session.all(:css, 'h1, p').size).to eq(4)
end
end
context 'with xpath selectors' do
it 'should find the first element using the given locator' do
expect(@session.all(:xpath, '//h1').first.text).to eq('This is a test')
expect(@session.all(:xpath, "//input[@id='test_field']").first.value).to eq('monkey')
end
it 'should use alternated regex for :id' do
expect(@session.all(:xpath, './/h2', id: /h2/).unfiltered_size).to eq 3
expect(@session.all(:xpath, './/h2', id: /h2(one|two)/).unfiltered_size).to eq 2
end
end
context 'with css as default selector' do
before { Capybara.default_selector = :css }
it 'should find the first element using the given locator' do
expect(@session.all('h1').first.text).to eq('This is a test')
expect(@session.all("input[id='test_field']").first.value).to eq('monkey')
end
end
context 'with visible filter' do
it 'should only find visible nodes when true' do
expect(@session.all(:css, 'a.simple', visible: true).size).to eq(1)
end
it 'should find nodes regardless of whether they are invisible when false' do
expect(@session.all(:css, 'a.simple', visible: false).size).to eq(2)
end
it 'should default to Capybara.ignore_hidden_elements' do
Capybara.ignore_hidden_elements = true
expect(@session.all(:css, 'a.simple').size).to eq(1)
Capybara.ignore_hidden_elements = false
expect(@session.all(:css, 'a.simple').size).to eq(2)
end
context 'with per session config', requires: [:psc] do
it 'should use the sessions ignore_hidden_elements', :psc do
Capybara.ignore_hidden_elements = true
@session.config.ignore_hidden_elements = false
expect(Capybara.ignore_hidden_elements).to be(true)
expect(@session.all(:css, 'a.simple').size).to eq(2)
@session.config.ignore_hidden_elements = true
expect(@session.all(:css, 'a.simple').size).to eq(1)
end
end
end
context 'with obscured filter', requires: [:css] do
it 'should only find nodes on top in the viewport when false' do
expect(@session.all(:css, 'a.simple', obscured: false).size).to eq(1)
end
it 'should not find nodes on top outside the viewport when false' do
expect(@session.all(:link, 'Download Me', obscured: false).size).to eq(0)
@session.scroll_to(@session.find_link('Download Me'))
expect(@session.all(:link, 'Download Me', obscured: false).size).to eq(1)
end
it 'should find top nodes outside the viewport when true' do
expect(@session.all(:link, 'Download Me', obscured: true).size).to eq(1)
@session.scroll_to(@session.find_link('Download Me'))
expect(@session.all(:link, 'Download Me', obscured: true).size).to eq(0)
end
it 'should only find non-top nodes when true' do
# Also need visible: false so visibility is ignored
expect(@session.all(:css, 'a.simple', visible: false, obscured: true).size).to eq(1)
end
end
context 'with element count filters' do
context ':count' do
it 'should succeed when the number of elements founds matches the expectation' do
expect { @session.all(:css, 'h1, p', count: 4) }.not_to raise_error
end
it 'should raise ExpectationNotMet when the number of elements founds does not match the expectation' do
expect { @session.all(:css, 'h1, p', count: 5) }.to raise_error(Capybara::ExpectationNotMet)
end
end
context ':minimum' do
it 'should succeed when the number of elements founds matches the expectation' do
expect { @session.all(:css, 'h1, p', minimum: 0) }.not_to raise_error
end
it 'should raise ExpectationNotMet when the number of elements founds does not match the expectation' do
expect { @session.all(:css, 'h1, p', minimum: 5) }.to raise_error(Capybara::ExpectationNotMet)
end
end
context ':maximum' do
it 'should succeed when the number of elements founds matches the expectation' do
expect { @session.all(:css, 'h1, p', maximum: 4) }.not_to raise_error
end
it 'should raise ExpectationNotMet when the number of elements founds does not match the expectation' do
expect { @session.all(:css, 'h1, p', maximum: 0) }.to raise_error(Capybara::ExpectationNotMet)
end
end
context ':between' do
it 'should succeed when the number of elements founds matches the expectation' do
expect { @session.all(:css, 'h1, p', between: 2..7) }.not_to raise_error
end
it 'should raise ExpectationNotMet when the number of elements founds does not match the expectation' do
expect { @session.all(:css, 'h1, p', between: 0..3) }.to raise_error(Capybara::ExpectationNotMet)
end
it 'treats an endless range as minimum' do
expect { @session.all(:css, 'h1, p', between: 2..) }.not_to raise_error
expect { @session.all(:css, 'h1, p', between: 5..) }.to raise_error(Capybara::ExpectationNotMet)
end
it 'treats a beginless range as maximum' do
expect { @session.all(:css, 'h1, p', between: ..7) }.not_to raise_error
expect { @session.all(:css, 'h1, p', between: ..3) }.to raise_error(Capybara::ExpectationNotMet)
end
end
context 'with multiple count filters' do
it 'ignores other filters when :count is specified' do
o = { count: 4,
minimum: 5,
maximum: 0,
between: 0..3 }
expect { @session.all(:css, 'h1, p', **o) }.not_to raise_error
end
context 'with no :count expectation' do
it 'fails if :minimum is not met' do
o = { minimum: 5,
maximum: 4,
between: 2..7 }
expect { @session.all(:css, 'h1, p', **o) }.to raise_error(Capybara::ExpectationNotMet)
end
it 'fails if :maximum is not met' do
o = { minimum: 0,
maximum: 0,
between: 2..7 }
expect { @session.all(:css, 'h1, p', **o) }.to raise_error(Capybara::ExpectationNotMet)
end
it 'fails if :between is not met' do
o = { minimum: 0,
maximum: 4,
between: 0..3 }
expect { @session.all(:css, 'h1, p', **o) }.to raise_error(Capybara::ExpectationNotMet)
end
it 'succeeds if all combineable expectations are met' do
o = { minimum: 0,
maximum: 4,
between: 2..7 }
expect { @session.all(:css, 'h1, p', **o) }.not_to raise_error
end
end
end
end
context 'within a scope' do
before do
@session.visit('/with_scope')
end
it 'should find any element using the given locator' do
@session.within(:xpath, "//div[@id='for_bar']") do
expect(@session.all('.//li').size).to eq(2)
end
end
end
it 'should have #find_all as an alias' do
expect(Capybara::Node::Finders.instance_method(:all)).to eq Capybara::Node::Finders.instance_method(:find_all)
expect(@session.find_all('//p').size).to eq(3)
end
end
| ruby | MIT | b3325b198464b806f07ec2011ceb532d6d5cf4ab | 2026-01-04T15:38:10.098638Z | false |
teamcapybara/capybara | https://github.com/teamcapybara/capybara/blob/b3325b198464b806f07ec2011ceb532d6d5cf4ab/lib/capybara/spec/session/assert_current_path_spec.rb | lib/capybara/spec/session/assert_current_path_spec.rb | # frozen_string_literal: true
Capybara::SpecHelper.spec '#assert_current_path' do
before do
@session.visit('/with_js')
end
it 'should not raise if the page has the given current path' do
expect { @session.assert_current_path('/with_js') }.not_to raise_error
end
it 'should allow regexp matches' do
expect { @session.assert_current_path(/w[a-z]{3}_js/) }.not_to raise_error
end
it 'should wait for current_path', requires: [:js] do
@session.click_link('Change page')
expect { @session.assert_current_path('/with_html') }.not_to raise_error
end
it 'should raise if the page has not the given current_path' do
expect { @session.assert_current_path('/with_html') }.to raise_error(Capybara::ExpectationNotMet, 'expected "/with_js" to equal "/with_html"')
end
it 'should check query options' do
@session.visit('/with_js?test=test')
expect { @session.assert_current_path('/with_js?test=test') }.not_to raise_error
end
it 'should compare the full url' do
expect { @session.assert_current_path(%r{\Ahttp://[^/]*/with_js\Z}, url: true) }.not_to raise_error
end
it 'should ignore the query' do
@session.visit('/with_js?test=test')
expect { @session.assert_current_path('/with_js', ignore_query: true) }.not_to raise_error
end
it 'should not cause an exception when current_url is nil' do
allow(@session).to receive(:current_url).and_return(nil)
allow(@session.page).to receive(:current_url).and_return(nil) if @session.respond_to? :page
expect { @session.assert_current_path(nil) }.not_to raise_error
end
end
Capybara::SpecHelper.spec '#assert_no_current_path?' do
before do
@session.visit('/with_js')
end
it 'should raise if the page has the given current_path' do
expect { @session.assert_no_current_path('/with_js') }.to raise_error(Capybara::ExpectationNotMet)
end
it 'should allow regexp matches' do
expect { @session.assert_no_current_path(/monkey/) }.not_to raise_error
end
it 'should wait for current_path to disappear', requires: [:js] do
@session.click_link('Change page')
expect { @session.assert_no_current_path('/with_js') }.not_to raise_error
end
it 'should not raise if the page has not the given current_path' do
expect { @session.assert_no_current_path('/with_html') }.not_to raise_error
end
it 'should not cause an exception when current_url is nil' do
allow(@session).to receive(:current_url).and_return(nil)
allow(@session.page).to receive(:current_url).and_return(nil) if @session.respond_to? :page
expect { @session.assert_no_current_path('/with_html') }.not_to raise_error
end
end
| ruby | MIT | b3325b198464b806f07ec2011ceb532d6d5cf4ab | 2026-01-04T15:38:10.098638Z | false |
teamcapybara/capybara | https://github.com/teamcapybara/capybara/blob/b3325b198464b806f07ec2011ceb532d6d5cf4ab/lib/capybara/spec/session/within_spec.rb | lib/capybara/spec/session/within_spec.rb | # frozen_string_literal: true
Capybara::SpecHelper.spec '#within' do
before do
@session.visit('/with_scope')
end
context 'with CSS selector' do
it 'should click links in the given scope' do
@session.within(:css, '#for_bar li:first-child') do
@session.click_link('Go')
end
expect(@session).to have_content('Bar')
end
it 'should assert content in the given scope' do
@session.within(:css, '#for_foo') do
expect(@session).not_to have_content('First Name')
end
expect(@session).to have_content('First Name')
end
it 'should accept additional options' do
@session.within(:css, '#for_bar li', text: 'With Simple HTML') do
@session.click_link('Go')
end
expect(@session).to have_content('Bar')
end
it 'should reload the node if the page is changed' do
@session.within(:css, '#for_foo') do
@session.visit('/with_scope_other')
expect(@session).to have_content('Different text')
end
end
it 'should reload multiple nodes if the page is changed' do
@session.within(:css, '#for_bar') do
@session.within(:css, 'form[action="/redirect"]') do
@session.refresh
expect(@session).to have_content('First Name')
end
end
end
it 'should error if the page is changed and a matching node no longer exists' do
@session.within(:css, '#for_foo') do
@session.visit('/')
expect { @session.text }.to raise_error(StandardError)
end
end
it 'should pass scope element to the block' do
@session.within(:css, '#another_foo') do |scope|
expect(scope).to match_css('#another_foo')
end
end
it 'should scope click', requires: [:js] do
@session.within(:css, '#another_foo') do |scope|
@session.click
expect(scope).to have_text('I was clicked')
end
end
end
context 'with XPath selector' do
it 'should click links in the given scope' do
@session.within(:xpath, "//div[@id='for_bar']//li[contains(.,'With Simple HTML')]") do
@session.click_link('Go')
end
expect(@session).to have_content('Bar')
end
end
context 'with the default selector' do
it 'should use XPath' do
@session.within("//div[@id='for_bar']//li[contains(.,'With Simple HTML')]") do
@session.click_link('Go')
end
expect(@session).to have_content('Bar')
end
end
context 'with Node rather than selector' do
it 'should click links in the given scope' do
node_of_interest = @session.find(:css, '#for_bar li', text: 'With Simple HTML')
@session.within(node_of_interest) do
@session.click_link('Go')
end
expect(@session).to have_content('Bar')
end
end
context 'with the default selector set to CSS' do
before { Capybara.default_selector = :css }
after { Capybara.default_selector = :xpath }
it 'should use CSS' do
@session.within('#for_bar li', text: 'With Simple HTML') do
@session.click_link('Go')
end
expect(@session).to have_content('Bar')
end
end
context 'with nested scopes' do
it 'should respect the inner scope' do
@session.within("//div[@id='for_bar']") do
@session.within(".//li[contains(.,'Bar')]") do
@session.click_link('Go')
end
end
expect(@session).to have_content('Another World')
end
it 'should respect the outer scope' do
@session.within("//div[@id='another_foo']") do
@session.within(".//li[contains(.,'With Simple HTML')]") do
@session.click_link('Go')
end
end
expect(@session).to have_content('Hello world')
end
end
it 'should raise an error if the scope is not found on the page' do
expect do
@session.within("//div[@id='doesnotexist']") do
end
end.to raise_error(Capybara::ElementNotFound)
end
it 'should restore the scope when an error is raised' do
expect do
@session.within("//div[@id='for_bar']") do
expect do
expect do
@session.within(".//div[@id='doesnotexist']") do
end
end.to raise_error(Capybara::ElementNotFound)
end.not_to change { @session.has_xpath?(".//div[@id='another_foo']") }.from(false)
end
end.not_to change { @session.has_xpath?(".//div[@id='another_foo']") }.from(true)
end
it 'should fill in a field and click a button' do
@session.within("//li[contains(.,'Bar')]") do
@session.click_button('Go')
end
expect(extract_results(@session)['first_name']).to eq('Peter')
@session.visit('/with_scope')
@session.within("//li[contains(.,'Bar')]") do
@session.fill_in('First Name', with: 'Dagobert')
@session.click_button('Go')
end
expect(extract_results(@session)['first_name']).to eq('Dagobert')
end
it 'should have #within_element as an alias' do
expect(Capybara::Session.instance_method(:within)).to eq Capybara::Session.instance_method(:within_element)
@session.within_element(:css, '#for_foo') do
expect(@session).not_to have_content('First Name')
end
end
end
Capybara::SpecHelper.spec '#within_fieldset' do
before do
@session.visit('/fieldsets')
end
it 'should restrict scope to a fieldset given by id' do
@session.within_fieldset('villain_fieldset') do
@session.fill_in('Name', with: 'Goldfinger')
@session.click_button('Create')
end
expect(extract_results(@session)['villain_name']).to eq('Goldfinger')
end
it 'should restrict scope to a fieldset given by legend' do
@session.within_fieldset('Villain') do
@session.fill_in('Name', with: 'Goldfinger')
@session.click_button('Create')
end
expect(extract_results(@session)['villain_name']).to eq('Goldfinger')
end
end
Capybara::SpecHelper.spec '#within_table' do
before do
@session.visit('/tables')
end
it 'should restrict scope to a fieldset given by id' do
@session.within_table('girl_table') do
@session.fill_in('Name', with: 'Christmas')
@session.click_button('Create')
end
expect(extract_results(@session)['girl_name']).to eq('Christmas')
end
it 'should restrict scope to a fieldset given by legend' do
@session.within_table('Villain') do
@session.fill_in('Name', with: 'Quantum')
@session.click_button('Create')
end
expect(extract_results(@session)['villain_name']).to eq('Quantum')
end
end
| ruby | MIT | b3325b198464b806f07ec2011ceb532d6d5cf4ab | 2026-01-04T15:38:10.098638Z | false |
teamcapybara/capybara | https://github.com/teamcapybara/capybara/blob/b3325b198464b806f07ec2011ceb532d6d5cf4ab/lib/capybara/spec/session/check_spec.rb | lib/capybara/spec/session/check_spec.rb | # frozen_string_literal: true
Capybara::SpecHelper.spec '#check' do
before do
@session.visit('/form')
end
describe "'checked' attribute" do
it 'should be true if checked' do
@session.check('Terms of Use')
expect(@session.find(:xpath, "//input[@id='form_terms_of_use']")['checked']).to be_truthy
end
it 'should be false if unchecked' do
expect(@session.find(:xpath, "//input[@id='form_terms_of_use']")['checked']).to be_falsey
end
end
it 'should trigger associated events', requires: [:js] do
@session.visit('/with_js')
@session.check('checkbox_with_event')
expect(@session).to have_css('#checkbox_event_triggered')
end
describe 'checking' do
it 'should not change an already checked checkbox' do
expect(@session.find(:xpath, "//input[@id='form_pets_dog']")).to be_checked
@session.check('form_pets_dog')
expect(@session.find(:xpath, "//input[@id='form_pets_dog']")).to be_checked
end
it 'should check an unchecked checkbox' do
expect(@session.find(:xpath, "//input[@id='form_pets_cat']")).not_to be_checked
@session.check('form_pets_cat')
expect(@session.find(:xpath, "//input[@id='form_pets_cat']")).to be_checked
end
end
describe 'unchecking' do
it 'should not change an already unchecked checkbox' do
expect(@session.find(:xpath, "//input[@id='form_pets_cat']")).not_to be_checked
@session.uncheck('form_pets_cat')
expect(@session.find(:xpath, "//input[@id='form_pets_cat']")).not_to be_checked
end
it 'should uncheck a checked checkbox' do
expect(@session.find(:xpath, "//input[@id='form_pets_dog']")).to be_checked
@session.uncheck('form_pets_dog')
expect(@session.find(:xpath, "//input[@id='form_pets_dog']")).not_to be_checked
end
end
it 'should check a checkbox by id' do
@session.check('form_pets_cat')
@session.click_button('awesome')
expect(extract_results(@session)['pets']).to include('dog', 'cat', 'hamster')
end
it 'should check a checkbox by label' do
@session.check('Cat')
@session.click_button('awesome')
expect(extract_results(@session)['pets']).to include('dog', 'cat', 'hamster')
end
it 'should work without a locator string' do
@session.check(id: 'form_pets_cat')
@session.click_button('awesome')
expect(extract_results(@session)['pets']).to include('dog', 'cat', 'hamster')
end
it 'should be able to check itself if no locator specified' do
cb = @session.find(:id, 'form_pets_cat')
cb.check
@session.click_button('awesome')
expect(extract_results(@session)['pets']).to include('dog', 'cat', 'hamster')
end
it 'casts to string' do
@session.check(:form_pets_cat)
@session.click_button('awesome')
expect(extract_results(@session)['pets']).to include('dog', 'cat', 'hamster')
end
context "with a locator that doesn't exist" do
it 'should raise an error' do
msg = /Unable to find checkbox "does not exist"/
expect do
@session.check('does not exist')
end.to raise_error(Capybara::ElementNotFound, msg)
end
end
context 'with a disabled checkbox' do
it 'should raise an error' do
msg = 'Unable to find visible checkbox "Disabled Checkbox" that is not disabled'
expect do
@session.check('Disabled Checkbox')
end.to raise_error(Capybara::ElementNotFound, msg)
end
end
context 'with :exact option' do
it 'should accept partial matches when false' do
@session.check('Ham', exact: false)
@session.click_button('awesome')
expect(extract_results(@session)['pets']).to include('hamster')
end
it 'should not accept partial matches when true' do
expect do
@session.check('Ham', exact: true)
end.to raise_error(Capybara::ElementNotFound)
end
end
context 'with `option` option' do
it 'can check boxes by their value' do
@session.check('form[pets][]', option: 'cat')
@session.click_button('awesome')
expect(extract_results(@session)['pets']).to include('cat')
end
it 'should alias `with`' do
@session.check('form[pets][]', with: 'cat')
@session.click_button('awesome')
expect(extract_results(@session)['pets']).to include('cat')
end
it 'should raise an error if option not found' do
expect do
@session.check('form[pets][]', option: 'elephant')
end.to raise_error(Capybara::ElementNotFound)
end
end
context 'when checkbox hidden' do
context 'with Capybara.automatic_label_click == true' do
around do |spec|
old_click_label, Capybara.automatic_label_click = Capybara.automatic_label_click, true
spec.run
Capybara.automatic_label_click = old_click_label
end
it 'should check via clicking the label with :for attribute if possible' do
expect(@session.find(:checkbox, 'form_cars_tesla', unchecked: true, visible: :hidden)).to be_truthy
@session.check('form_cars_tesla')
@session.click_button('awesome')
expect(extract_results(@session)['cars']).to include('tesla')
end
it 'should check via clicking the wrapping label if possible' do
expect(@session.find(:checkbox, 'form_cars_mclaren', unchecked: true, visible: :hidden)).to be_truthy
@session.check('form_cars_mclaren')
@session.click_button('awesome')
expect(extract_results(@session)['cars']).to include('mclaren')
end
it 'should check via clicking the label with :for attribute if locator nil' do
cb = @session.find(:checkbox, 'form_cars_tesla', unchecked: true, visible: :hidden)
cb.check
@session.click_button('awesome')
expect(extract_results(@session)['cars']).to include('tesla')
end
it 'should check self via clicking the wrapping label if locator nil' do
cb = @session.find(:checkbox, 'form_cars_mclaren', unchecked: true, visible: :hidden)
cb.check
@session.click_button('awesome')
expect(extract_results(@session)['cars']).to include('mclaren')
end
it 'should not click the label if unneeded' do
expect(@session.find(:checkbox, 'form_cars_jaguar', checked: true, visible: :hidden)).to be_truthy
@session.check('form_cars_jaguar')
@session.click_button('awesome')
expect(extract_results(@session)['cars']).to include('jaguar')
end
it 'should raise original error when no label available' do
expect { @session.check('form_cars_ariel') }.to raise_error(Capybara::ElementNotFound, /Unable to find visible checkbox "form_cars_ariel"/)
end
it 'should raise error if not allowed to click label' do
expect { @session.check('form_cars_mclaren', allow_label_click: false) }.to raise_error(Capybara::ElementNotFound, /Unable to find visible checkbox "form_cars_mclaren"/)
end
end
context 'with Capybara.automatic_label_click == false' do
around do |spec|
old_label_click, Capybara.automatic_label_click = Capybara.automatic_label_click, false
spec.run
Capybara.automatic_label_click = old_label_click
end
it 'should raise error if checkbox not visible' do
expect { @session.check('form_cars_mclaren') }.to raise_error(Capybara::ElementNotFound, /Unable to find visible checkbox "form_cars_mclaren"/)
end
it 'should include node filter in error if verified' do
expect { @session.check('form_cars_maserati') }.to raise_error(Capybara::ElementNotFound, 'Unable to find visible checkbox "form_cars_maserati" that is not disabled')
end
context 'with allow_label_click == true' do
it 'should check via the label if input is hidden' do
expect(@session.find(:checkbox, 'form_cars_tesla', unchecked: true, visible: :hidden)).to be_truthy
@session.check('form_cars_tesla', allow_label_click: true)
@session.click_button('awesome')
expect(extract_results(@session)['cars']).to include('tesla')
end
it 'should not wait the full time if label can be clicked' do
expect(@session.find(:checkbox, 'form_cars_tesla', unchecked: true, visible: :hidden)).to be_truthy
start_time = Time.now
@session.check('form_cars_tesla', allow_label_click: true, wait: 10)
end_time = Time.now
expect(end_time - start_time).to be < 10
end
it 'should check via the label if input is moved off the left edge of the page' do
expect(@session.find(:checkbox, 'form_cars_pagani', unchecked: true, visible: :all)).to be_truthy
@session.check('form_cars_pagani', allow_label_click: true)
@session.click_button('awesome')
expect(extract_results(@session)['cars']).to include('pagani')
end
it 'should check via the label if input is visible but blocked by another element' do
expect(@session.find(:checkbox, 'form_cars_bugatti', unchecked: true, visible: :all)).to be_truthy
@session.check('form_cars_bugatti', allow_label_click: true)
@session.click_button('awesome')
expect(extract_results(@session)['cars']).to include('bugatti')
end
it 'should check via label if multiple labels' do
expect(@session).to have_field('multi_label_checkbox', checked: false, visible: :hidden)
@session.check('Label to click', allow_label_click: true)
expect(@session).to have_field('multi_label_checkbox', checked: true, visible: :hidden)
end
end
context 'with allow_label_click options', requires: [:js] do
it 'should allow offsets to click location on label' do
Capybara.w3c_click_offset = false
expect(@session.find(:checkbox, 'form_cars_lotus', unchecked: true, visible: :hidden)).to be_truthy
@session.check('form_cars_lotus', allow_label_click: { x: 90, y: 10 })
@session.click_button('awesome')
expect(extract_results(@session)['cars']).to include('lotus')
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/spec/session/current_url_spec.rb | lib/capybara/spec/session/current_url_spec.rb | # frozen_string_literal: true
require 'capybara/spec/test_app'
Capybara::SpecHelper.spec '#current_url, #current_path, #current_host' do
before :all do # rubocop:disable RSpec/BeforeAfterAll
@servers = Array.new(2) { Capybara::Server.new(TestApp.new).boot }
# sanity check
expect(@servers[0].port).not_to eq(@servers[1].port) # rubocop:disable RSpec/ExpectInHook
expect(@servers.map(&:port)).not_to include 80 # rubocop:disable RSpec/ExpectInHook
end
def bases
@servers.map { |s| "http://#{s.host}:#{s.port}" }
end
def should_be_on(server_index, path = '/host', scheme = 'http')
# Check that we are on /host on the given server
s = @servers[server_index]
expect(@session).to have_current_path("#{scheme}://#{s.host}:#{s.port}#{path}", url: true)
expect(@session.current_url.chomp('?')).to eq("#{scheme}://#{s.host}:#{s.port}#{path}")
expect(@session.current_host).to eq("#{scheme}://#{s.host}") # no port
expect(@session.current_path).to eq(path.split('#')[0])
# Server should agree with us
expect(@session).to have_content("Current host is #{scheme}://#{s.host}:#{s.port}") if path == '/host'
end
def visit_host_links
@session.visit("#{bases[0]}/host_links?absolute_host=#{bases[1]}")
end
it 'is affected by visiting a page directly' do
@session.visit("#{bases[0]}/host")
should_be_on 0
end
it 'returns to the app host when visiting a relative url' do
Capybara.app_host = bases[1]
@session.visit("#{bases[0]}/host")
should_be_on 0
@session.visit('/host')
should_be_on 1
Capybara.app_host = nil
end
it 'is affected by setting Capybara.app_host' do
Capybara.app_host = bases[0]
@session.visit('/host')
should_be_on 0
Capybara.app_host = bases[1]
@session.visit('/host')
should_be_on 1
Capybara.app_host = nil
end
it 'is unaffected by following a relative link' do
visit_host_links
@session.click_link('Relative Host')
should_be_on 0
end
it 'is affected by following an absolute link' do
visit_host_links
@session.click_link('Absolute Host')
should_be_on 1
end
it 'is unaffected by posting through a relative form' do
visit_host_links
@session.click_button('Relative Host')
should_be_on 0
end
it 'is affected by posting through an absolute form' do
visit_host_links
@session.click_button('Absolute Host')
should_be_on 1
end
it 'is affected by following a redirect' do
@session.visit("#{bases[0]}/redirect")
should_be_on 0, '/landed'
end
it 'maintains fragment' do
@session.visit("#{bases[0]}/redirect#fragment")
should_be_on 0, '/landed#fragment'
end
it 'redirects to a fragment' do
@session.visit("#{bases[0]}/redirect_with_fragment")
should_be_on 0, '/landed#with_fragment'
end
it 'is affected by pushState', requires: [:js] do
@session.visit('/with_js')
@session.execute_script("window.history.pushState({}, '', '/pushed')")
expect(@session.current_path).to eq('/pushed')
end
it 'is affected by replaceState', requires: [:js] do
@session.visit('/with_js')
@session.execute_script("window.history.replaceState({}, '', '/replaced')")
expect(@session.current_path).to eq('/replaced')
end
it "doesn't raise exception on a nil current_url", requires: [:driver] do
allow(@session.driver).to receive(:current_url).and_return(nil)
@session.visit('/')
expect { @session.current_url }.not_to raise_exception
expect { @session.current_path }.not_to raise_exception
end
context 'within iframe', requires: [:frames] do
it 'should get the url of the top level browsing context' do
@session.visit('/within_frames')
expect(@session.current_url).to match(/within_frames\z/)
@session.within_frame('frameOne') do
expect(@session.current_url).to match(/within_frames\z/)
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/spec/session/unselect_spec.rb | lib/capybara/spec/session/unselect_spec.rb | # frozen_string_literal: true
Capybara::SpecHelper.spec '#unselect' do
before do
@session.visit('/form')
end
context 'with multiple select' do
it 'should unselect an option from a select box by id' do
@session.unselect('Commando', from: 'form_underwear')
@session.click_button('awesome')
expect(extract_results(@session)['underwear']).to include('Briefs', 'Boxerbriefs')
expect(extract_results(@session)['underwear']).not_to include('Commando')
end
it 'should unselect an option without a select box' do
@session.unselect('Commando')
@session.click_button('awesome')
expect(extract_results(@session)['underwear']).to include('Briefs', 'Boxerbriefs')
expect(extract_results(@session)['underwear']).not_to include('Commando')
end
it 'should unselect an option from a select box by label' do
@session.unselect('Commando', from: 'Underwear')
@session.click_button('awesome')
expect(extract_results(@session)['underwear']).to include('Briefs', 'Boxerbriefs')
expect(extract_results(@session)['underwear']).not_to include('Commando')
end
it 'should favour exact matches to option labels' do
@session.unselect('Briefs', from: 'Underwear')
@session.click_button('awesome')
expect(extract_results(@session)['underwear']).to include('Commando', 'Boxerbriefs')
expect(extract_results(@session)['underwear']).not_to include('Briefs')
end
it 'should escape quotes' do
@session.unselect("Frenchman's Pantalons", from: 'Underwear')
@session.click_button('awesome')
expect(extract_results(@session)['underwear']).not_to include("Frenchman's Pantalons")
end
it 'casts to string' do
@session.unselect(:Briefs, from: :Underwear)
@session.click_button('awesome')
expect(extract_results(@session)['underwear']).to include('Commando', 'Boxerbriefs')
expect(extract_results(@session)['underwear']).not_to include('Briefs')
end
end
context 'with single select' do
it 'should raise an error' do
expect { @session.unselect('English', from: 'form_locale') }.to raise_error(Capybara::UnselectNotAllowed)
end
end
context "with a locator that doesn't exist" do
it 'should raise an error' do
msg = /Unable to find select box "does not exist"/
expect do
@session.unselect('foo', from: 'does not exist')
end.to raise_error(Capybara::ElementNotFound, msg)
end
end
context "with an option that doesn't exist" do
it 'should raise an error' do
msg = /^Unable to find option "Does not Exist" within/
expect do
@session.unselect('Does not Exist', from: 'form_underwear')
end.to raise_error(Capybara::ElementNotFound, msg)
end
end
context 'with :exact option' do
context 'when `false`' do
it 'can match select box approximately' do
@session.unselect('Boxerbriefs', from: 'Under', exact: false)
@session.click_button('awesome')
expect(extract_results(@session)['underwear']).not_to include('Boxerbriefs')
end
it 'can match option approximately' do
@session.unselect('Boxerbr', from: 'Underwear', exact: false)
@session.click_button('awesome')
expect(extract_results(@session)['underwear']).not_to include('Boxerbriefs')
end
it 'can match option approximately when :from not given' do
@session.unselect('Boxerbr', exact: false)
@session.click_button('awesome')
expect(extract_results(@session)['underwear']).not_to include('Boxerbriefs')
end
end
context 'when `true`' do
it 'can match select box approximately' do
expect do
@session.unselect('Boxerbriefs', from: 'Under', exact: true)
end.to raise_error(Capybara::ElementNotFound)
end
it 'can match option approximately' do
expect do
@session.unselect('Boxerbr', from: 'Underwear', exact: true)
end.to raise_error(Capybara::ElementNotFound)
end
it 'can match option approximately when :from not given' do
expect do
@session.unselect('Boxerbr', exact: true)
end.to raise_error(Capybara::ElementNotFound)
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/spec/session/has_title_spec.rb | lib/capybara/spec/session/has_title_spec.rb | # frozen_string_literal: true
Capybara::SpecHelper.spec '#has_title?' do
before do
@session.visit('/with_js')
end
it 'should be true if the page has the given title' do
expect(@session).to have_title('with_js')
expect(@session.has_title?('with_js')).to be true
end
it 'should allow regexp matches' do
expect(@session).to have_title(/w[a-z]{3}_js/)
expect(@session).not_to have_title(/monkey/)
end
it 'should wait for title', requires: [:js] do
@session.click_link('Change title')
expect(@session).to have_title('changed title')
end
it 'should be false if the page has not the given title' do
expect(@session).not_to have_title('monkey')
expect(@session.has_title?('monkey')).to be false
end
it 'should default to exact: false matching' do
expect(@session).to have_title('with_js', exact: false)
expect(@session).to have_title('with_', exact: false)
end
it 'should match exactly if exact: true option passed' do
expect(@session).to have_title('with_js', exact: true)
expect(@session).not_to have_title('with_', exact: true)
expect(@session.has_title?('with_js', exact: true)).to be true
expect(@session.has_title?('with_', exact: true)).to be false
end
it 'should match partial if exact: false option passed' do
expect(@session).to have_title('with_js', exact: false)
expect(@session).to have_title('with_', exact: false)
end
end
Capybara::SpecHelper.spec '#has_no_title?' do
before do
@session.visit('/with_js')
end
it 'should be false if the page has the given title' do
expect(@session).not_to have_no_title('with_js')
end
it 'should allow regexp matches' do
expect(@session).not_to have_no_title(/w[a-z]{3}_js/)
expect(@session).to have_no_title(/monkey/)
end
it 'should wait for title to disappear', requires: [:js] do
Capybara.using_wait_time(5) do
@session.click_link('Change title') # triggers title change after 400ms
expect(@session).to have_no_title('with_js')
end
end
it 'should be true if the page has not the given title' do
expect(@session).to have_no_title('monkey')
expect(@session.has_no_title?('monkey')).to be true
end
end
| ruby | MIT | b3325b198464b806f07ec2011ceb532d6d5cf4ab | 2026-01-04T15:38:10.098638Z | false |
teamcapybara/capybara | https://github.com/teamcapybara/capybara/blob/b3325b198464b806f07ec2011ceb532d6d5cf4ab/lib/capybara/spec/session/has_sibling_spec.rb | lib/capybara/spec/session/has_sibling_spec.rb | # frozen_string_literal: true
Capybara::SpecHelper.spec '#have_sibling' do
before do
@session.visit('/with_html')
end
it 'should assert a prior sibling element using the given locator' do
el = @session.find(:css, '#mid_sibling')
expect(el).to have_sibling(:css, '#pre_sibling')
end
it 'should assert a following sibling element using the given locator' do
el = @session.find(:css, '#mid_sibling')
expect(el).to have_sibling(:css, '#post_sibling')
end
it 'should not raise an error if there are multiple matches' do
el = @session.find(:css, '#mid_sibling')
expect(el).to have_sibling(:css, 'div')
end
it 'should allow counts to be specified' do
el = @session.find(:css, '#mid_sibling')
expect(el).to have_sibling(:css, 'div').exactly(2).times
expect do
expect(el).to have_sibling(:css, 'div').once
end.to raise_error(RSpec::Expectations::ExpectationNotMetError)
end
end
Capybara::SpecHelper.spec '#have_no_sibling' do
before do
@session.visit('/with_html')
end
it 'should assert no matching sibling' do
el = @session.find(:css, '#mid_sibling')
expect(el).to have_no_sibling(:css, '#not_a_sibling')
expect(el).not_to have_sibling(:css, '#not_a_sibling')
end
it 'should raise if there are matching siblings' do
el = @session.find(:css, '#mid_sibling')
expect do
expect(el).to have_no_sibling(:css, '#pre_sibling')
end.to raise_error(RSpec::Expectations::ExpectationNotMetError)
end
end
| ruby | MIT | b3325b198464b806f07ec2011ceb532d6d5cf4ab | 2026-01-04T15:38:10.098638Z | false |
teamcapybara/capybara | https://github.com/teamcapybara/capybara/blob/b3325b198464b806f07ec2011ceb532d6d5cf4ab/lib/capybara/spec/session/has_field_spec.rb | lib/capybara/spec/session/has_field_spec.rb | # frozen_string_literal: true
Capybara::SpecHelper.spec '#has_field' do
before { @session.visit('/form') }
it 'should be true if the field is on the page' do
expect(@session).to have_field('Dog')
expect(@session).to have_field('form_description')
expect(@session).to have_field('Region')
expect(@session).to have_field(:Region)
end
it 'should be false if the field is not on the page' do
expect(@session).not_to have_field('Monkey')
end
context 'with value' do
it 'should be true if a field with the given value is on the page' do
expect(@session).to have_field('First Name', with: 'John')
expect(@session).to have_field('First Name', with: /^Joh/)
expect(@session).to have_field('Phone', with: '+1 555 7021')
expect(@session).to have_field('Street', with: 'Sesame street 66')
expect(@session).to have_field('Description', with: 'Descriptive text goes here')
end
it 'should be false if the given field is not on the page' do
expect(@session).not_to have_field('First Name', with: 'Peter')
expect(@session).not_to have_field('First Name', with: /eter$/)
expect(@session).not_to have_field('Wrong Name', with: 'John')
expect(@session).not_to have_field('Description', with: 'Monkey')
end
it 'should be true after the field has been filled in with the given value' do
@session.fill_in('First Name', with: 'Jonas')
expect(@session).to have_field('First Name', with: 'Jonas')
expect(@session).to have_field('First Name', with: /ona/)
end
it 'should be false after the field has been filled in with a different value' do
@session.fill_in('First Name', with: 'Jonas')
expect(@session).not_to have_field('First Name', with: 'John')
expect(@session).not_to have_field('First Name', with: /John|Paul|George|Ringo/)
end
it 'should output filter errors if only one element matched the selector but failed the filters' do
@session.fill_in('First Name', with: 'Thomas')
expect do
expect(@session).to have_field('First Name', with: 'Jonas')
end.to raise_exception(RSpec::Expectations::ExpectationNotMetError, /Expected value to be "Jonas" but was "Thomas"/)
# native boolean node filter
expect do
expect(@session).to have_field('First Name', readonly: true)
end.to raise_exception(RSpec::Expectations::ExpectationNotMetError, /Expected readonly true but it wasn't/)
# inherited boolean node filter
expect do
expect(@session).to have_field('form_pets_cat', checked: true)
end.to raise_exception(RSpec::Expectations::ExpectationNotMetError, /Expected checked true but it wasn't/)
end
end
context 'with validation message', requires: [:html_validation] do
it 'should accept a regexp' do
@session.fill_in('form_zipcode', with: '1234')
expect(@session).to have_field('form_zipcode', validation_message: /match the requested format/)
expect(@session).not_to have_field('form_zipcode', validation_message: /random/)
end
it 'should accept a string' do
@session.fill_in('form_zipcode', with: '1234')
expect(@session).to have_field('form_zipcode', validation_message: 'Please match the requested format.')
expect(@session).not_to have_field('form_zipcode', validation_message: 'match the requested format.')
@session.fill_in('form_zipcode', with: '12345')
expect(@session).to have_field('form_zipcode', validation_message: '')
end
end
context 'with type' do
it 'should be true if a field with the given type is on the page' do
expect(@session).to have_field('First Name', type: 'text')
expect(@session).to have_field('Html5 Email', type: 'email')
expect(@session).to have_field('Html5 Multiple Email', type: 'email')
expect(@session).to have_field('Html5 Tel', type: 'tel')
expect(@session).to have_field('Description', type: 'textarea')
expect(@session).to have_field('Languages', type: 'select')
end
it 'should be false if the given field is not on the page' do
expect(@session).not_to have_field('First Name', type: 'textarea')
expect(@session).not_to have_field('Html5 Email', type: 'tel')
expect(@session).not_to have_field('Html5 Multiple Email', type: 'tel')
expect(@session).not_to have_field('Description', type: '')
expect(@session).not_to have_field('Description', type: 'email')
expect(@session).not_to have_field('Languages', type: 'textarea')
end
it 'it can find type="hidden" elements if explicity specified' do
expect(@session).to have_field('form[data]', with: 'TWTW', type: 'hidden')
end
end
context 'with multiple' do
it 'should be true if a field with the multiple attribute is on the page' do
expect(@session).to have_field('Html5 Multiple Email', multiple: true)
end
it 'should be false if a field without the multiple attribute is not on the page' do
expect(@session).not_to have_field('Html5 Multiple Email', multiple: false)
end
end
context 'with focused:', requires: [:active_element] do
it 'should be true if a field has focus' do
2.times { @session.send_keys(:tab) }
expect(@session).to have_field('An Input', focused: true)
end
it 'should be false if a field does not have focus' do
expect(@session).to have_field('An Input', focused: false)
end
end
context 'with valid', requires: [:js] do
it 'should be true if field is valid' do
@session.fill_in 'required', with: 'something'
@session.fill_in 'length', with: 'abcd'
expect(@session).to have_field('required', valid: true)
expect(@session).to have_field('length', valid: true)
end
it 'should be false if field is invalid' do
expect(@session).not_to have_field('required', valid: true)
expect(@session).to have_field('required', valid: false)
@session.fill_in 'length', with: 'abc'
expect(@session).not_to have_field('length', valid: true)
end
end
end
Capybara::SpecHelper.spec '#has_no_field' do
before { @session.visit('/form') }
it 'should be false if the field is on the page' do
expect(@session).not_to have_no_field('Dog')
expect(@session).not_to have_no_field('form_description')
expect(@session).not_to have_no_field('Region')
end
it 'should be true if the field is not on the page' do
expect(@session).to have_no_field('Monkey')
end
context 'with value' do
it 'should be false if a field with the given value is on the page' do
expect(@session).not_to have_no_field('First Name', with: 'John')
expect(@session).not_to have_no_field('Phone', with: '+1 555 7021')
expect(@session).not_to have_no_field('Street', with: 'Sesame street 66')
expect(@session).not_to have_no_field('Description', with: 'Descriptive text goes here')
end
it 'should be true if the given field is not on the page' do
expect(@session).to have_no_field('First Name', with: 'Peter')
expect(@session).to have_no_field('Wrong Name', with: 'John')
expect(@session).to have_no_field('Description', with: 'Monkey')
end
it 'should be false after the field has been filled in with the given value' do
@session.fill_in('First Name', with: 'Jonas')
expect(@session).not_to have_no_field('First Name', with: 'Jonas')
end
it 'should be true after the field has been filled in with a different value' do
@session.fill_in('First Name', with: 'Jonas')
expect(@session).to have_no_field('First Name', with: 'John')
end
end
context 'with type' do
it 'should be false if a field with the given type is on the page' do
expect(@session).not_to have_no_field('First Name', type: 'text')
expect(@session).not_to have_no_field('Html5 Email', type: 'email')
expect(@session).not_to have_no_field('Html5 Tel', type: 'tel')
expect(@session).not_to have_no_field('Description', type: 'textarea')
expect(@session).not_to have_no_field('Languages', type: 'select')
end
it 'should be true if the given field is not on the page' do
expect(@session).to have_no_field('First Name', type: 'textarea')
expect(@session).to have_no_field('Html5 Email', type: 'tel')
expect(@session).to have_no_field('Description', type: '')
expect(@session).to have_no_field('Description', type: 'email')
expect(@session).to have_no_field('Languages', type: 'textarea')
end
end
context 'with focused:', requires: [:active_element] do
it 'should be true if a field does not have focus when focused: true' do
expect(@session).to have_no_field('An Input', focused: true)
end
it 'should be false if a field has focus when focused: true' do
2.times { @session.send_keys(:tab) }
expect(@session).not_to have_no_field('An Input', focused: true)
end
end
end
Capybara::SpecHelper.spec '#has_checked_field?' do
before { @session.visit('/form') }
it 'should be true if a checked field is on the page' do
expect(@session).to have_checked_field('gender_female')
expect(@session).to have_checked_field('Hamster')
end
it 'should be true for disabled checkboxes if disabled: true' do
expect(@session).to have_checked_field('Disabled Checkbox', disabled: true)
end
it 'should be false if an unchecked field is on the page' do
expect(@session).not_to have_checked_field('form_pets_cat')
expect(@session).not_to have_checked_field('Male')
end
it 'should be false if no field is on the page' do
expect(@session).not_to have_checked_field('Does Not Exist')
end
it 'should be false for disabled checkboxes by default' do
expect(@session).not_to have_checked_field('Disabled Checkbox')
end
it 'should be false for disabled checkboxes if disabled: false' do
expect(@session).not_to have_checked_field('Disabled Checkbox', disabled: false)
end
it 'should be true for disabled checkboxes if disabled: :all' do
expect(@session).to have_checked_field('Disabled Checkbox', disabled: :all)
end
it 'should be true for enabled checkboxes if disabled: :all' do
expect(@session).to have_checked_field('gender_female', disabled: :all)
end
it 'should be true after an unchecked checkbox is checked' do
@session.check('form_pets_cat')
expect(@session).to have_checked_field('form_pets_cat')
end
it 'should be false after a checked checkbox is unchecked' do
@session.uncheck('form_pets_dog')
expect(@session).not_to have_checked_field('form_pets_dog')
end
it 'should be true after an unchecked radio button is chosen' do
@session.choose('gender_male')
expect(@session).to have_checked_field('gender_male')
end
it 'should be false after another radio button in the group is chosen' do
@session.choose('gender_male')
expect(@session).not_to have_checked_field('gender_female')
end
end
Capybara::SpecHelper.spec '#has_no_checked_field?' do
before { @session.visit('/form') }
it 'should be false if a checked field is on the page' do
expect(@session).not_to have_no_checked_field('gender_female')
expect(@session).not_to have_no_checked_field('Hamster')
end
it 'should be false for disabled checkboxes if disabled: true' do
expect(@session).not_to have_no_checked_field('Disabled Checkbox', disabled: true)
end
it 'should be true if an unchecked field is on the page' do
expect(@session).to have_no_checked_field('form_pets_cat')
expect(@session).to have_no_checked_field('Male')
end
it 'should be true if no field is on the page' do
expect(@session).to have_no_checked_field('Does Not Exist')
end
it 'should be true for disabled checkboxes by default' do
expect(@session).to have_no_checked_field('Disabled Checkbox')
end
it 'should be true for disabled checkboxes if disabled: false' do
expect(@session).to have_no_checked_field('Disabled Checkbox', disabled: false)
end
end
Capybara::SpecHelper.spec '#has_unchecked_field?' do
before { @session.visit('/form') }
it 'should be false if a checked field is on the page' do
expect(@session).not_to have_unchecked_field('gender_female')
expect(@session).not_to have_unchecked_field('Hamster')
end
it 'should be true if an unchecked field is on the page' do
expect(@session).to have_unchecked_field('form_pets_cat')
expect(@session).to have_unchecked_field('Male')
end
it 'should be true for disabled unchecked fields if disabled: true' do
expect(@session).to have_unchecked_field('Disabled Unchecked Checkbox', disabled: true)
end
it 'should be false if no field is on the page' do
expect(@session).not_to have_unchecked_field('Does Not Exist')
end
it 'should be false for disabled unchecked fields by default' do
expect(@session).not_to have_unchecked_field('Disabled Unchecked Checkbox')
end
it 'should be false for disabled unchecked fields if disabled: false' do
expect(@session).not_to have_unchecked_field('Disabled Unchecked Checkbox', disabled: false)
end
it 'should be false after an unchecked checkbox is checked' do
@session.check('form_pets_cat')
expect(@session).not_to have_unchecked_field('form_pets_cat')
end
it 'should be true after a checked checkbox is unchecked' do
@session.uncheck('form_pets_dog')
expect(@session).to have_unchecked_field('form_pets_dog')
end
it 'should be false after an unchecked radio button is chosen' do
@session.choose('gender_male')
expect(@session).not_to have_unchecked_field('gender_male')
end
it 'should be true after another radio button in the group is chosen' do
@session.choose('gender_male')
expect(@session).to have_unchecked_field('gender_female')
end
it 'should support locator-less usage' do
expect(@session.has_unchecked_field?(disabled: true, id: 'form_disabled_unchecked_checkbox')).to be true
expect(@session).to have_unchecked_field(disabled: true, id: 'form_disabled_unchecked_checkbox')
end
end
Capybara::SpecHelper.spec '#has_no_unchecked_field?' do
before { @session.visit('/form') }
it 'should be true if a checked field is on the page' do
expect(@session).to have_no_unchecked_field('gender_female')
expect(@session).to have_no_unchecked_field('Hamster')
end
it 'should be false if an unchecked field is on the page' do
expect(@session).not_to have_no_unchecked_field('form_pets_cat')
expect(@session).not_to have_no_unchecked_field('Male')
end
it 'should be false for disabled unchecked fields if disabled: true' do
expect(@session).not_to have_no_unchecked_field('Disabled Unchecked Checkbox', disabled: true)
end
it 'should be true if no field is on the page' do
expect(@session).to have_no_unchecked_field('Does Not Exist')
end
it 'should be true for disabled unchecked fields by default' do
expect(@session).to have_no_unchecked_field('Disabled Unchecked Checkbox')
end
it 'should be true for disabled unchecked fields if disabled: false' do
expect(@session).to have_no_unchecked_field('Disabled Unchecked Checkbox', disabled: false)
end
it 'should support locator-less usage' do
expect(@session.has_no_unchecked_field?(disabled: false, id: 'form_disabled_unchecked_checkbox')).to be true
expect(@session).to have_no_unchecked_field(disabled: false, id: 'form_disabled_unchecked_checkbox')
end
end
| ruby | MIT | b3325b198464b806f07ec2011ceb532d6d5cf4ab | 2026-01-04T15:38:10.098638Z | false |
teamcapybara/capybara | https://github.com/teamcapybara/capybara/blob/b3325b198464b806f07ec2011ceb532d6d5cf4ab/lib/capybara/spec/session/evaluate_async_script_spec.rb | lib/capybara/spec/session/evaluate_async_script_spec.rb | # frozen_string_literal: true
Capybara::SpecHelper.spec '#evaluate_async_script', requires: [:js] do
it 'should evaluate the given script and return whatever it produces' do
@session.visit('/with_js')
expect(@session.evaluate_async_script('arguments[0](4)')).to eq(4)
end
it 'should support passing elements as arguments to the script', requires: %i[js es_args] do
@session.visit('/with_js')
el = @session.find(:css, '#drag p')
result = @session.evaluate_async_script('arguments[2]([arguments[0].innerText, arguments[1]])', el, 'Doodle Funk')
expect(result).to eq ['This is a draggable element.', 'Doodle Funk']
end
it 'should support returning elements after asynchronous operation', requires: %i[js es_args] do
@session.visit('/with_js')
@session.find(:css, '#change') # ensure page has loaded and element is available
el = @session.evaluate_async_script("var cb = arguments[0]; setTimeout(function(){ cb(document.getElementById('change')) }, 100)")
expect(el).to be_instance_of(Capybara::Node::Element)
expect(el).to eq(@session.find(:css, '#change'))
end
end
| ruby | MIT | b3325b198464b806f07ec2011ceb532d6d5cf4ab | 2026-01-04T15:38:10.098638Z | false |
teamcapybara/capybara | https://github.com/teamcapybara/capybara/blob/b3325b198464b806f07ec2011ceb532d6d5cf4ab/lib/capybara/spec/session/has_css_spec.rb | lib/capybara/spec/session/has_css_spec.rb | # frozen_string_literal: true
Capybara::SpecHelper.spec '#has_css?' do
before do
@session.visit('/with_html')
end
it 'should be true if the given selector is on the page' do
expect(@session).to have_css('p')
expect(@session).to have_css('p a#foo')
end
it 'should warn when passed a symbol' do
# This was never a specifically accepted format but it has worked for a
# lot of versions.
# TODO: Remove in 4.0
allow(Capybara::Helpers).to receive(:warn).and_return(nil)
expect(@session).to have_css(:p)
expect(Capybara::Helpers).to have_received(:warn)
end
it 'should be false if the given selector is not on the page' do
expect(@session).not_to have_css('abbr')
expect(@session).not_to have_css('p a#doesnotexist')
expect(@session).not_to have_css('p.nosuchclass')
end
it 'should support :id option' do
expect(@session).to have_css('h2', id: 'h2one')
expect(@session).to have_css('h2')
expect(@session).to have_css('h2', id: /h2o/)
expect(@session).to have_css('li', id: /john|paul/)
end
it 'should support :class option' do
expect(@session).to have_css('li', class: 'guitarist')
expect(@session).to have_css('li', class: /guitar/)
expect(@session).to have_css('li', class: /guitar|drummer/)
expect(@session).to have_css('li', class: %w[beatle guitarist])
expect(@session).to have_css('li', class: /.*/)
end
context ':style option' do
it 'should support String' do
expect(@session).to have_css('p', style: 'line-height: 25px;')
expect do
expect(@session).to have_css('p', style: 'display: not_valid')
end.to raise_error(RSpec::Expectations::ExpectationNotMetError, /style attribute "display: not_valid"/)
end
it 'should support Regexp' do
expect(@session).to have_css('p', style: /-height: 2/)
expect do
expect(@session).to have_css('p', style: /not_valid/)
end.to raise_error(RSpec::Expectations::ExpectationNotMetError, %r{style attribute matching /not_valid/})
end
it 'should support Hash', requires: [:css] do
expect(@session).to have_css('p', style: { 'line-height': '25px' })
expect do
expect(@session).to have_css('p', style: { 'line-height': '30px' })
end.to raise_error(RSpec::Expectations::ExpectationNotMetError, /with styles \{:"line-height"=>"30px"\}/)
end
end
it 'should support case insensitive :class and :id options' do
expect(@session).to have_css('li', class: /UiTaRI/i)
expect(@session).to have_css('h2', id: /2ON/i)
end
context 'when scoped' do
it 'should look in the scope' do
@session.within "//p[@id='first']" do
expect(@session).to have_css('a#foo')
expect(@session).not_to have_css('a#red')
end
end
it 'should be able to generate an error message if the scope is a sibling' do
el = @session.find(:css, '#first')
@session.within el.sibling(:css, '#second') do
expect do
expect(@session).to have_css('a#not_on_page')
end.to raise_error(/there were no matches/)
end
end
it 'should be able to generate an error message if the scope is a sibling from XPath' do
el = @session.find(:css, '#first').find(:xpath, './following-sibling::*[1]') do
expect do
expect(el).to have_css('a#not_on_page')
end.to raise_error(/there were no matches/)
end
end
end
it 'should wait for content to appear', requires: [:js] do
Capybara.default_max_wait_time = 2
@session.visit('/with_js')
@session.click_link('Click me')
expect(@session).to have_css("input[type='submit'][value='New Here']")
end
context 'with predicates_wait == true' do
it 'should wait for content to appear', requires: [:js] do
Capybara.predicates_wait = true
Capybara.default_max_wait_time = 2
@session.visit('/with_js')
@session.click_link('Click me')
expect(@session.has_css?("input[type='submit'][value='New Here']")).to be true
end
end
context 'with predicates_wait == false' do
before do
Capybara.predicates_wait = false
Capybara.default_max_wait_time = 5
@session.visit('/with_js')
@session.click_link('Click me')
end
it 'should not wait for content to appear', requires: [:js] do
expect(@session.has_css?("input[type='submit'][value='New Here']")).to be false
end
it 'should should the default wait time if true is passed for :wait', requires: [:js] do
expect(@session.has_css?("input[type='submit'][value='New Here']", wait: true)).to be true
end
end
context 'with between' do
it 'should be true if the content occurs within the range given' do
expect(@session).to have_css('p', between: 1..4)
expect(@session).to have_css('p a#foo', between: 1..3)
expect(@session).to have_css('p a.doesnotexist', between: 0..8)
end
it 'should be false if the content occurs more or fewer times than range' do
expect(@session).not_to have_css('p', between: 6..11)
expect(@session).not_to have_css('p a#foo', between: 4..7)
expect(@session).not_to have_css('p a.doesnotexist', between: 3..8)
end
end
context 'with count' do
it 'should be true if the content occurs the given number of times' do
expect(@session).to have_css('p', count: 3)
expect(@session).to have_css('p').exactly(3).times
expect(@session).to have_css('p a#foo', count: 1)
expect(@session).to have_css('p a#foo').once
expect(@session).to have_css('p a.doesnotexist', count: 0)
expect(@session).to have_css('li', class: /guitar|drummer/, count: 4)
expect(@session).to have_css('li', id: /john|paul/, class: /guitar|drummer/, count: 2)
expect(@session).to have_css('li', class: %w[beatle guitarist], count: 2)
expect(@session).to have_css('p', style: 'line-height: 25px;', count: 1)
expect(@session).to have_css('p', style: /-height: 2/, count: 1)
end
it 'should be true if the content occurs the given number of times in CSS processing drivers', requires: [:css] do
expect(@session).to have_css('p', style: { 'line-height': '25px' }, count: 1)
end
it 'should be false if the content occurs a different number of times than the given' do
expect(@session).not_to have_css('p', count: 6)
expect(@session).not_to have_css('p').exactly(5).times
expect(@session).not_to have_css('p a#foo', count: 2)
expect(@session).not_to have_css('p a.doesnotexist', count: 1)
end
it 'should coerce count to an integer' do
expect(@session).to have_css('p', count: '3')
expect(@session).to have_css('p a#foo', count: '1')
end
end
context 'with maximum' do
it 'should be true when content occurs same or fewer times than given' do
expect(@session).to have_css('h2.head', maximum: 5) # edge case
expect(@session).to have_css('h2', maximum: 10)
expect(@session).to have_css('h2').at_most(10).times
expect(@session).to have_css('p a.doesnotexist', maximum: 1)
expect(@session).to have_css('p a.doesnotexist', maximum: 0)
end
it 'should be false when content occurs more times than given' do
# expect(@session).not_to have_css('h2.head', maximum: 4) # edge case
# expect(@session).not_to have_css('h2', maximum: 3)
expect(@session).not_to have_css('h2').at_most(3).times
# expect(@session).not_to have_css('p', maximum: 1)
end
it 'should coerce maximum to an integer' do
expect(@session).to have_css('h2.head', maximum: '5') # edge case
expect(@session).to have_css('h2', maximum: '10')
end
end
context 'with minimum' do
it 'should be true when content occurs same or more times than given' do
expect(@session).to have_css('h2.head', minimum: 5) # edge case
expect(@session).to have_css('h2', minimum: 3)
expect(@session).to have_css('h2').at_least(2).times
expect(@session).to have_css('p a.doesnotexist', minimum: 0)
end
it 'should be false when content occurs fewer times than given' do
expect(@session).not_to have_css('h2.head', minimum: 6) # edge case
expect(@session).not_to have_css('h2', minimum: 8)
expect(@session).not_to have_css('h2').at_least(8).times
expect(@session).not_to have_css('p', minimum: 10)
expect(@session).not_to have_css('p a.doesnotexist', minimum: 1)
end
it 'should coerce minimum to an integer' do
expect(@session).to have_css('h2.head', minimum: '5') # edge case
expect(@session).to have_css('h2', minimum: '3')
end
end
context 'with text' do
it 'should discard all matches where the given string is not contained' do
expect(@session).to have_css('p a', text: 'Redirect', count: 1)
expect(@session).not_to have_css('p a', text: 'Doesnotexist')
end
it 'should discard all matches where the given regexp is not matched' do
expect(@session).to have_css('p a', text: /re[dab]i/i, count: 1)
expect(@session).not_to have_css('p a', text: /Red$/)
end
end
context 'with spatial requirements', requires: [:spatial] do
before do
@session.visit('/spatial')
end
let :center do
@session.find(:css, '.center')
end
it 'accepts spatial options' do
expect(@session).to have_css('div', above: center).thrice
expect(@session).to have_css('div', above: center, right_of: center).once
end
it 'supports spatial sugar' do
expect(@session).to have_css('div').left_of(center).thrice
expect(@session).to have_css('div').below(center).right_of(center).once
expect(@session).to have_css('div').near(center).exactly(8).times
end
end
it 'should allow escapes in the CSS selector' do
expect(@session).to have_css('p[data-random="abc\\\\def"]')
expect(@session).to have_css("p[data-random='#{Capybara::Selector::CSS.escape('abc\def')}']")
end
end
Capybara::SpecHelper.spec '#has_no_css?' do
before do
@session.visit('/with_html')
end
it 'should be false if the given selector is on the page' do
expect(@session).not_to have_no_css('p')
expect(@session).not_to have_no_css('p a#foo')
end
it 'should be true if the given selector is not on the page' do
expect(@session).to have_no_css('abbr')
expect(@session).to have_no_css('p a#doesnotexist')
expect(@session).to have_no_css('p.nosuchclass')
end
it 'should respect scopes' do
@session.within "//p[@id='first']" do
expect(@session).not_to have_no_css('a#foo')
expect(@session).to have_no_css('a#red')
end
end
it 'should wait for content to disappear', requires: [:js] do
Capybara.default_max_wait_time = 2
@session.visit('/with_js')
@session.click_link('Click me')
expect(@session).to have_no_css('p#change')
end
context 'with between' do
it 'should be false if the content occurs within the range given' do
expect(@session).not_to have_no_css('p', between: 1..4)
expect(@session).not_to have_no_css('p a#foo', between: 1..3)
expect(@session).not_to have_no_css('p a.doesnotexist', between: 0..2)
end
it 'should be true if the content occurs more or fewer times than range' do
expect(@session).to have_no_css('p', between: 6..11)
expect(@session).to have_no_css('p a#foo', between: 4..7)
expect(@session).to have_no_css('p a.doesnotexist', between: 3..8)
end
end
context 'with count' do
it 'should be false if the content is on the page the given number of times' do
expect(@session).not_to have_no_css('p', count: 3)
expect(@session).not_to have_no_css('p a#foo', count: 1)
expect(@session).not_to have_no_css('p a.doesnotexist', count: 0)
end
it 'should be true if the content is on the page the given number of times' do
expect(@session).to have_no_css('p', count: 6)
expect(@session).to have_no_css('p a#foo', count: 2)
expect(@session).to have_no_css('p a.doesnotexist', count: 1)
end
it 'should coerce count to an integer' do
expect(@session).not_to have_no_css('p', count: '3')
expect(@session).not_to have_no_css('p a#foo', count: '1')
end
end
context 'with maximum' do
it 'should be false when content occurs same or fewer times than given' do
expect(@session).not_to have_no_css('h2.head', maximum: 5) # edge case
expect(@session).not_to have_no_css('h2', maximum: 10)
expect(@session).not_to have_no_css('p a.doesnotexist', maximum: 0)
end
it 'should be true when content occurs more times than given' do
expect(@session).to have_no_css('h2.head', maximum: 4) # edge case
expect(@session).to have_no_css('h2', maximum: 3)
expect(@session).to have_no_css('p', maximum: 1)
end
it 'should coerce maximum to an integer' do
expect(@session).not_to have_no_css('h2.head', maximum: '5') # edge case
expect(@session).not_to have_no_css('h2', maximum: '10')
end
end
context 'with minimum' do
it 'should be false when content occurs same or more times than given' do
expect(@session).not_to have_no_css('h2.head', minimum: 5) # edge case
expect(@session).not_to have_no_css('h2', minimum: 3)
expect(@session).not_to have_no_css('p a.doesnotexist', minimum: 0)
end
it 'should be true when content occurs fewer times than given' do
expect(@session).to have_no_css('h2.head', minimum: 6) # edge case
expect(@session).to have_no_css('h2', minimum: 8)
expect(@session).to have_no_css('p', minimum: 15)
expect(@session).to have_no_css('p a.doesnotexist', minimum: 1)
end
it 'should coerce minimum to an integer' do
expect(@session).not_to have_no_css('h2.head', minimum: '4') # edge case
expect(@session).not_to have_no_css('h2', minimum: '3')
end
end
context 'with text' do
it 'should discard all matches where the given string is not contained' do
expect(@session).not_to have_no_css('p a', text: 'Redirect', count: 1)
expect(@session).to have_no_css('p a', text: 'Doesnotexist')
end
it 'should discard all matches where the given regexp is not matched' do
expect(@session).not_to have_no_css('p a', text: /re[dab]i/i, count: 1)
expect(@session).to have_no_css('p a', text: /Red$/)
end
end
end
| ruby | MIT | b3325b198464b806f07ec2011ceb532d6d5cf4ab | 2026-01-04T15:38:10.098638Z | false |
teamcapybara/capybara | https://github.com/teamcapybara/capybara/blob/b3325b198464b806f07ec2011ceb532d6d5cf4ab/lib/capybara/spec/session/scroll_spec.rb | lib/capybara/spec/session/scroll_spec.rb | # frozen_string_literal: true
Capybara::SpecHelper.spec '#scroll_to', requires: [:scroll] do
before do
@session.visit('/scroll')
end
it 'can scroll an element to the top of the viewport' do
el = @session.find(:css, '#scroll')
@session.scroll_to(el, align: :top)
expect(el.evaluate_script('this.getBoundingClientRect().top')).to be_within(1).of(0)
end
it 'can scroll an element to the bottom of the viewport' do
el = @session.find(:css, '#scroll')
@session.scroll_to(el, align: :bottom)
el_bottom = el.evaluate_script('this.getBoundingClientRect().bottom')
viewport_bottom = el.evaluate_script('document.documentElement.clientHeight')
expect(el_bottom).to be_within(1).of(viewport_bottom)
end
it 'can scroll an element to the center of the viewport' do
el = @session.find(:css, '#scroll')
@session.scroll_to(el, align: :center)
el_center = el.evaluate_script('(function(rect){return (rect.top + rect.bottom)/2})(this.getBoundingClientRect())')
viewport_bottom = el.evaluate_script('document.documentElement.clientHeight')
expect(el_center).to be_within(2).of(viewport_bottom / 2)
end
it 'can scroll the window to the vertical top' do
@session.scroll_to :bottom
@session.scroll_to :top
expect(@session.evaluate_script('[window.scrollX || window.pageXOffset, window.scrollY || window.pageYOffset]')).to eq [0, 0]
end
it 'can scroll the window to the vertical bottom' do
@session.scroll_to :bottom
max_scroll = @session.evaluate_script('document.documentElement.scrollHeight - document.documentElement.clientHeight')
scrolled_location_x, scrolled_location_y = @session.evaluate_script('[window.scrollX || window.pageXOffset, window.scrollY || window.pageYOffset]')
expect(scrolled_location_x).to be_within(0.5).of(0)
expect(scrolled_location_y).to be_within(0.5).of(max_scroll)
end
it 'can scroll the window to the vertical center' do
@session.scroll_to :center
max_scroll = @session.evaluate_script('document.documentElement.scrollHeight - document.documentElement.clientHeight')
expect(@session.evaluate_script('[window.scrollX || window.pageXOffset, window.scrollY || window.pageYOffset]')).to match [0, be_within(1).of(max_scroll / 2)]
end
it 'can scroll the window to specific location' do
@session.scroll_to 100, 100
expect(@session.evaluate_script('[window.scrollX || window.pageXOffset, window.scrollY || window.pageYOffset]')).to eq [100, 100]
end
it 'can scroll an element to the top of the scrolling element' do
scrolling_element = @session.find(:css, '#scrollable')
el = scrolling_element.find(:css, '#inner')
scrolling_element.scroll_to(el, align: :top)
scrolling_element_top = scrolling_element.evaluate_script('this.getBoundingClientRect().top')
expect(el.evaluate_script('this.getBoundingClientRect().top')).to be_within(3).of(scrolling_element_top)
end
it 'can scroll an element to the bottom of the scrolling element' do
scrolling_element = @session.find(:css, '#scrollable')
el = scrolling_element.find(:css, '#inner')
scrolling_element.scroll_to(el, align: :bottom)
el_bottom = el.evaluate_script('this.getBoundingClientRect().bottom')
scroller_bottom = scrolling_element.evaluate_script('this.getBoundingClientRect().top + this.clientHeight')
expect(el_bottom).to be_within(1).of(scroller_bottom)
end
it 'can scroll an element to the center of the scrolling element' do
scrolling_element = @session.find(:css, '#scrollable')
el = scrolling_element.find(:css, '#inner')
scrolling_element.scroll_to(el, align: :center)
el_center = el.evaluate_script('(function(rect){return (rect.top + rect.bottom)/2})(this.getBoundingClientRect())')
scrollable_center = scrolling_element.evaluate_script('(this.clientHeight / 2) + this.getBoundingClientRect().top')
# Firefox reports floats and can be slightly outside 1 difference - make 2 instaed
expect(el_center).to be_within(2).of(scrollable_center)
end
it 'can scroll the scrolling element to the top' do
scrolling_element = @session.find(:css, '#scrollable')
scrolling_element.scroll_to :bottom
scrolling_element.scroll_to :top
expect(scrolling_element.evaluate_script('[this.scrollLeft, this.scrollTop]')).to eq [0, 0]
end
it 'can scroll the scrolling element to the bottom' do
scrolling_element = @session.find(:css, '#scrollable')
scrolling_element.scroll_to :bottom
max_scroll = scrolling_element.evaluate_script('this.scrollHeight - this.clientHeight')
expect(scrolling_element.evaluate_script('[this.scrollLeft, this.scrollTop]')).to eq [0, max_scroll]
end
it 'can scroll the scrolling element to the vertical center' do
scrolling_element = @session.find(:css, '#scrollable')
scrolling_element.scroll_to :center
max_scroll = scrolling_element.evaluate_script('this.scrollHeight - this.clientHeight')
expect(scrolling_element.evaluate_script('[this.scrollLeft, this.scrollTop]')).to match [0, be_within(1).of(max_scroll / 2)]
end
it 'can scroll the scrolling element to specific location' do
scrolling_element = @session.find(:css, '#scrollable')
scrolling_element.scroll_to 100, 100
expect(scrolling_element.evaluate_script('[this.scrollLeft, this.scrollTop]')).to eq [100, 100]
end
it 'can scroll the window by a specific amount' do
@session.scroll_to(:current, offset: [50, 75])
expect(@session.evaluate_script('[window.scrollX || window.pageXOffset, window.scrollY || window.pageYOffset]')).to eq [50, 75]
end
it 'can scroll the scroll the scrolling element by a specific amount' do
scrolling_element = @session.find(:css, '#scrollable')
scrolling_element.scroll_to 100, 100
scrolling_element.scroll_to(:current, offset: [-50, 50])
expect(scrolling_element.evaluate_script('[this.scrollLeft, this.scrollTop]')).to eq [50, 150]
end
end
| ruby | MIT | b3325b198464b806f07ec2011ceb532d6d5cf4ab | 2026-01-04T15:38:10.098638Z | false |
teamcapybara/capybara | https://github.com/teamcapybara/capybara/blob/b3325b198464b806f07ec2011ceb532d6d5cf4ab/lib/capybara/spec/session/matches_style_spec.rb | lib/capybara/spec/session/matches_style_spec.rb | # frozen_string_literal: true
Capybara::SpecHelper.spec '#matches_style?', requires: [:css] do
before do
@session.visit('/with_html')
end
it 'should be true if the element has the given style' do
expect(@session.find(:css, '#first')).to match_style(display: 'block')
expect(@session.find(:css, '#first').matches_style?(display: 'block')).to be true
expect(@session.find(:css, '#second')).to match_style('display' => 'inline')
expect(@session.find(:css, '#second').matches_style?('display' => 'inline')).to be true
end
it 'should be false if the element does not have the given style' do
expect(@session.find(:css, '#first').matches_style?('display' => 'inline')).to be false
expect(@session.find(:css, '#second').matches_style?(display: 'block')).to be false
end
it 'allows Regexp for value matching' do
expect(@session.find(:css, '#first')).to match_style(display: /^bl/)
expect(@session.find(:css, '#first').matches_style?('display' => /^bl/)).to be true
expect(@session.find(:css, '#first').matches_style?(display: /^in/)).to be false
end
# rubocop:disable Capybara/MatchStyle
it 'deprecated has_style?' do
expect { have_style(display: /^bl/) }.to \
output(/have_style is deprecated/).to_stderr
el = @session.find(:css, '#first')
allow(Capybara::Helpers).to receive(:warn).and_return(nil)
el.has_style?('display' => /^bl/)
expect(Capybara::Helpers).to have_received(:warn)
end
# rubocop:enable Capybara/MatchStyle
end
| ruby | MIT | b3325b198464b806f07ec2011ceb532d6d5cf4ab | 2026-01-04T15:38:10.098638Z | false |
teamcapybara/capybara | https://github.com/teamcapybara/capybara/blob/b3325b198464b806f07ec2011ceb532d6d5cf4ab/lib/capybara/spec/session/go_back_spec.rb | lib/capybara/spec/session/go_back_spec.rb | # frozen_string_literal: true
Capybara::SpecHelper.spec '#go_back', requires: [:js] do
it 'should fetch a response from the driver from the previous page' do
@session.visit('/')
expect(@session).to have_content('Hello world!')
@session.visit('/foo')
expect(@session).to have_content('Another World')
@session.go_back
expect(@session).to have_content('Hello world!')
end
end
| ruby | MIT | b3325b198464b806f07ec2011ceb532d6d5cf4ab | 2026-01-04T15:38:10.098638Z | false |
teamcapybara/capybara | https://github.com/teamcapybara/capybara/blob/b3325b198464b806f07ec2011ceb532d6d5cf4ab/lib/capybara/spec/session/html_spec.rb | lib/capybara/spec/session/html_spec.rb | # frozen_string_literal: true
# NOTE: This file uses `sleep` to sync up parts of the tests. This is only implemented like this
# because of the methods being tested. In tests using Capybara this type of behavior should be implemented
# using Capybara provided assertions with builtin waiting behavior.
Capybara::SpecHelper.spec '#html' do
it 'should return the unmodified page body' do
@session.visit('/')
expect(@session.html).to include('Hello world!')
end
it 'should return the current state of the page', requires: [:js] do
@session.visit('/with_js')
sleep 1
expect(@session.html).to include('I changed it')
expect(@session.html).not_to include('This is text')
end
end
Capybara::SpecHelper.spec '#source' do
it 'should return the unmodified page source' do
@session.visit('/')
expect(@session.source).to include('Hello world!')
end
it 'should return the current state of the page', requires: [:js] do
@session.visit('/with_js')
sleep 1
expect(@session.source).to include('I changed it')
expect(@session.source).not_to include('This is text')
end
end
Capybara::SpecHelper.spec '#body' do
it 'should return the unmodified page source' do
@session.visit('/')
expect(@session.body).to include('Hello world!')
end
it 'should return the current state of the page', requires: [:js] do
@session.visit('/with_js')
sleep 1
expect(@session.body).to include('I changed it')
expect(@session.body).not_to include('This is text')
end
end
| ruby | MIT | b3325b198464b806f07ec2011ceb532d6d5cf4ab | 2026-01-04T15:38:10.098638Z | false |
teamcapybara/capybara | https://github.com/teamcapybara/capybara/blob/b3325b198464b806f07ec2011ceb532d6d5cf4ab/lib/capybara/spec/session/uncheck_spec.rb | lib/capybara/spec/session/uncheck_spec.rb | # frozen_string_literal: true
Capybara::SpecHelper.spec '#uncheck' do
before do
@session.visit('/form')
end
it 'should uncheck a checkbox by id' do
@session.uncheck('form_pets_hamster')
@session.click_button('awesome')
expect(extract_results(@session)['pets']).to include('dog')
expect(extract_results(@session)['pets']).not_to include('hamster')
end
it 'should uncheck a checkbox by label' do
@session.uncheck('Hamster')
@session.click_button('awesome')
expect(extract_results(@session)['pets']).to include('dog')
expect(extract_results(@session)['pets']).not_to include('hamster')
end
it 'should work without a locator string' do
@session.uncheck(id: 'form_pets_hamster')
@session.click_button('awesome')
expect(extract_results(@session)['pets']).to include('dog')
expect(extract_results(@session)['pets']).not_to include('hamster')
end
it 'should be able to uncheck itself if no locator specified' do
cb = @session.find(:id, 'form_pets_hamster')
cb.uncheck
@session.click_button('awesome')
expect(extract_results(@session)['pets']).to include('dog')
expect(extract_results(@session)['pets']).not_to include('hamster')
end
it 'casts to string' do
@session.uncheck(:form_pets_hamster)
@session.click_button('awesome')
expect(extract_results(@session)['pets']).to include('dog')
expect(extract_results(@session)['pets']).not_to include('hamster')
end
context 'with :exact option' do
it 'should accept partial matches when false' do
@session.uncheck('Ham', exact: false)
@session.click_button('awesome')
expect(extract_results(@session)['pets']).not_to include('hamster')
end
it 'should not accept partial matches when true' do
expect do
@session.uncheck('Ham', exact: true)
end.to raise_error(Capybara::ElementNotFound)
end
end
context 'when checkbox hidden' do
context 'with Capybara.automatic_label_click == true' do
around do |spec|
old_click_label, Capybara.automatic_label_click = Capybara.automatic_label_click, true
spec.run
Capybara.automatic_label_click = old_click_label
end
it 'should uncheck via clicking the label with :for attribute if possible' do
expect(@session.find(:checkbox, 'form_cars_jaguar', checked: true, visible: :hidden)).to be_truthy
@session.uncheck('form_cars_jaguar')
@session.click_button('awesome')
expect(extract_results(@session)['cars']).not_to include('jaguar')
end
it 'should uncheck via clicking the wrapping label if possible' do
expect(@session.find(:checkbox, 'form_cars_koenigsegg', checked: true, visible: :hidden)).to be_truthy
@session.uncheck('form_cars_koenigsegg')
@session.click_button('awesome')
expect(extract_results(@session)['cars']).not_to include('koenigsegg')
end
it 'should not click the label if unneeded' do
expect(@session.find(:checkbox, 'form_cars_tesla', unchecked: true, visible: :hidden)).to be_truthy
@session.uncheck('form_cars_tesla')
@session.click_button('awesome')
expect(extract_results(@session)['cars']).not_to include('tesla')
end
it 'should raise original error when no label available' do
expect { @session.uncheck('form_cars_porsche') }.to raise_error(Capybara::ElementNotFound, /Unable to find visible checkbox "form_cars_porsche"/)
end
it 'should raise error if not allowed to click label' do
expect { @session.uncheck('form_cars_jaguar', allow_label_click: false) }.to raise_error(Capybara::ElementNotFound, /Unable to find visible checkbox "form_cars_jaguar"/)
end
it 'should include node filter description in error if necessary' do
expect { @session.uncheck('form_cars_maserati', allow_label_click: false) }.to raise_error(Capybara::ElementNotFound, 'Unable to find visible checkbox "form_cars_maserati" that is not disabled')
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/spec/session/save_and_open_screenshot_spec.rb | lib/capybara/spec/session/save_and_open_screenshot_spec.rb | # frozen_string_literal: true
require 'launchy'
Capybara::SpecHelper.spec '#save_and_open_screenshot' do
before do
@session.visit '/'
end
it 'opens file from the default directory', requires: [:screenshot] do
expected_file_regex = /capybara-\d+\.png/
allow(@session.driver).to receive(:save_screenshot)
allow(Launchy).to receive(:open)
@session.save_and_open_screenshot
expect(@session.driver).to have_received(:save_screenshot)
.with(expected_file_regex, any_args)
expect(Launchy).to have_received(:open).with(expected_file_regex)
end
it 'opens file from the provided directory', requires: [:screenshot] do
custom_path = 'screenshots/1.png'
allow(@session.driver).to receive(:save_screenshot)
allow(Launchy).to receive(:open)
@session.save_and_open_screenshot(custom_path)
expect(@session.driver).to have_received(:save_screenshot)
.with(/#{custom_path}$/, any_args)
expect(Launchy).to have_received(:open).with(/#{custom_path}$/)
end
context 'when launchy cannot be required' do
it 'prints out a correct warning message', requires: [:screenshot] do
file_path = File.join(Dir.tmpdir, 'test.png')
allow(@session).to receive(:warn)
allow(@session).to receive(:require).with('launchy').and_raise(LoadError)
@session.save_and_open_screenshot(file_path)
expect(@session).to have_received(:warn).with("File saved to #{file_path}.\nPlease install the launchy gem to open the file automatically.")
end
end
end
| ruby | MIT | b3325b198464b806f07ec2011ceb532d6d5cf4ab | 2026-01-04T15:38:10.098638Z | false |
teamcapybara/capybara | https://github.com/teamcapybara/capybara/blob/b3325b198464b806f07ec2011ceb532d6d5cf4ab/lib/capybara/spec/session/fill_in_spec.rb | lib/capybara/spec/session/fill_in_spec.rb | # frozen_string_literal: true
Capybara::SpecHelper.spec '#fill_in' do
before do
@session.visit('/form')
end
it 'should fill in a text field by id' do
@session.fill_in('form_first_name', with: 'Harry')
@session.click_button('awesome')
expect(extract_results(@session)['first_name']).to eq('Harry')
end
it 'should fill in a text field by name' do
@session.fill_in('form[last_name]', with: 'Green')
@session.click_button('awesome')
expect(extract_results(@session)['last_name']).to eq('Green')
end
it 'should fill in a text field by label without for' do
@session.fill_in('First Name', with: 'Harry')
@session.click_button('awesome')
expect(extract_results(@session)['first_name']).to eq('Harry')
end
it 'should fill in a url field by label without for' do
@session.fill_in('Html5 Url', with: 'http://www.avenueq.com')
@session.click_button('html5_submit')
expect(extract_results(@session)['html5_url']).to eq('http://www.avenueq.com')
end
it 'should fill in a textarea by id' do
@session.fill_in('form_description', with: 'Texty text')
@session.click_button('awesome')
expect(extract_results(@session)['description']).to eq('Texty text')
end
it 'should fill in a textarea by label' do
@session.fill_in('Description', with: 'Texty text')
@session.click_button('awesome')
expect(extract_results(@session)['description']).to eq('Texty text')
end
it 'should fill in a textarea by name' do
@session.fill_in('form[description]', with: 'Texty text')
@session.click_button('awesome')
expect(extract_results(@session)['description']).to eq('Texty text')
end
it 'should fill in a textarea in a reasonable time by default' do
textarea = @session.find(:fillable_field, 'form[description]')
value = 'a' * 4000
start = Time.now
textarea.fill_in(with: value)
expect(Time.now.to_f).to be_within(0.25).of start.to_f
expect(textarea.value).to eq value
end
it 'should fill in a password field by id' do
@session.fill_in('form_password', with: 'supasikrit')
@session.click_button('awesome')
expect(extract_results(@session)['password']).to eq('supasikrit')
end
context 'Date/Time' do
it 'should fill in a date input' do
date = Date.today
@session.fill_in('form_date', with: date)
@session.click_button('awesome')
expect(Date.parse(extract_results(@session)['date'])).to eq date
end
it 'should fill in a time input' do
time = Time.new(2018, 3, 9, 15, 26)
@session.fill_in('form_time', with: time)
@session.click_button('awesome')
results = extract_results(@session)['time']
expect(Time.parse(results).strftime('%r')).to eq time.strftime('%r')
end
it 'should fill in a datetime input' do
dt = Time.new(2018, 3, 13, 9, 53)
@session.fill_in('form_datetime', with: dt)
@session.click_button('awesome')
expect(Time.parse(extract_results(@session)['datetime'])).to eq dt
end
end
it 'should handle HTML in a textarea' do
@session.fill_in('form_description', with: 'is <strong>very</strong> secret!')
@session.click_button('awesome')
expect(extract_results(@session)['description']).to eq('is <strong>very</strong> secret!')
end
it 'should handle newlines in a textarea' do
@session.fill_in('form_description', with: "\nSome text\n")
@session.click_button('awesome')
expect(extract_results(@session)['description']).to eq("\r\nSome text\r\n")
end
it 'should handle carriage returns with line feeds in a textarea correctly' do
@session.fill_in('form_description', with: "\r\nSome text\r\n")
@session.click_button('awesome')
expect(extract_results(@session)['description']).to eq("\r\nSome text\r\n")
end
it 'should fill in a color field' do
@session.fill_in('Html5 Color', with: '#112233')
@session.click_button('html5_submit')
expect(extract_results(@session)['html5_color']).to eq('#112233')
end
describe 'with input[type="range"]' do
it 'should set the range slider correctly' do
@session.fill_in('form_age', with: 51)
@session.click_button('awesome')
expect(extract_results(@session)['age'].to_f).to eq 51
end
it 'should set the range slider to valid values' do
@session.fill_in('form_age', with: '37.6')
@session.click_button('awesome')
expect(extract_results(@session)['age'].to_f).to eq 37.5
end
it 'should respect the range slider limits' do
@session.fill_in('form_age', with: '3')
@session.click_button('awesome')
expect(extract_results(@session)['age'].to_f).to eq 13
end
end
it 'should fill in a field with a custom type' do
@session.fill_in('Schmooo', with: 'Schmooo is the game')
@session.click_button('awesome')
expect(extract_results(@session)['schmooo']).to eq('Schmooo is the game')
end
it 'should fill in a field without a type' do
@session.fill_in('Phone', with: '+1 555 7022')
@session.click_button('awesome')
expect(extract_results(@session)['phone']).to eq('+1 555 7022')
end
it 'should fill in a text field respecting its maxlength attribute' do
@session.fill_in('Zipcode', with: '52071350')
@session.click_button('awesome')
expect(extract_results(@session)['zipcode']).to eq('52071')
end
it 'should fill in a password field by name' do
@session.fill_in('form[password]', with: 'supasikrit')
@session.click_button('awesome')
expect(extract_results(@session)['password']).to eq('supasikrit')
end
it 'should fill in a password field by label' do
@session.fill_in('Password', with: 'supasikrit')
@session.click_button('awesome')
expect(extract_results(@session)['password']).to eq('supasikrit')
end
it 'should fill in a password field by name' do
@session.fill_in('form[password]', with: 'supasikrit')
@session.click_button('awesome')
expect(extract_results(@session)['password']).to eq('supasikrit')
end
it 'should fill in a field based on current value' do
@session.fill_in(id: /form.*name/, currently_with: 'John', with: 'Thomas')
@session.click_button('awesome')
expect(extract_results(@session)['first_name']).to eq('Thomas')
end
it 'should fill in a field based on type' do
@session.fill_in(type: 'schmooo', with: 'Schmooo for all')
@session.click_button('awesome')
expect(extract_results(@session)['schmooo']).to eq('Schmooo for all')
end
it 'should be able to fill in element called on when no locator passed' do
field = @session.find(:fillable_field, 'form[password]')
field.fill_in(with: 'supasikrit')
@session.click_button('awesome')
expect(extract_results(@session)['password']).to eq('supasikrit')
end
it "should throw an exception if a hash containing 'with' is not provided" do
expect { @session.fill_in 'Name' }.to raise_error(ArgumentError, /with/)
end
it 'should wait for asynchronous load', requires: [:js] do
Capybara.default_max_wait_time = 2
@session.visit('/with_js')
@session.click_link('Click me')
@session.fill_in('new_field', with: 'Testing...')
end
it 'casts to string' do
@session.fill_in(:form_first_name, with: :Harry)
@session.click_button('awesome')
expect(extract_results(@session)['first_name']).to eq('Harry')
end
it 'casts to string if field has maxlength' do
@session.fill_in(:form_zipcode, with: 1234567)
@session.click_button('awesome')
expect(extract_results(@session)['zipcode']).to eq('12345')
end
it 'fills in a field if default_set_options is nil' do
Capybara.default_set_options = nil
@session.fill_in(:form_first_name, with: 'Thomas')
@session.click_button('awesome')
expect(extract_results(@session)['first_name']).to eq('Thomas')
end
context 'on a pre-populated textfield with a reformatting onchange', requires: [:js] do
it 'should only trigger onchange once' do
@session.visit('/with_js')
# Click somewhere on the page to ensure focus is acquired. Without this FF won't generate change events for some reason???
@session.find(:css, 'h1', text: 'FooBar').click
@session.fill_in('with_change_event', with: 'some value')
# click outside the field to trigger the change event
@session.find(:css, 'h1', text: 'FooBar').click
expect(@session.find(:css, '.change_event_triggered', match: :one)).to have_text 'some value'
end
it 'should trigger change when clearing field' do
@session.visit('/with_js')
@session.fill_in('with_change_event', with: '')
# click outside the field to trigger the change event
@session.find(:css, 'h1', text: 'FooBar').click
expect(@session).to have_selector(:css, '.change_event_triggered', match: :one)
end
end
context 'with ignore_hidden_fields' do
before { Capybara.ignore_hidden_elements = true }
after { Capybara.ignore_hidden_elements = false }
it 'should not find a hidden field' do
msg = /Unable to find visible field "Super Secret"/
expect do
@session.fill_in('Super Secret', with: '777')
end.to raise_error(Capybara::ElementNotFound, msg)
end
end
context "with a locator that doesn't exist" do
it 'should raise an error' do
msg = /Unable to find field "does not exist"/
expect do
@session.fill_in('does not exist', with: 'Blah blah')
end.to raise_error(Capybara::ElementNotFound, msg)
end
end
context 'on a disabled field' do
it 'should raise an error' do
expect do
@session.fill_in('Disabled Text Field', with: 'Blah blah')
end.to raise_error(Capybara::ElementNotFound)
end
end
context 'with :exact option' do
it 'should accept partial matches when false' do
@session.fill_in('Explanation', with: 'Dude', exact: false)
@session.click_button('awesome')
expect(extract_results(@session)['name_explanation']).to eq('Dude')
end
it 'should not accept partial matches when true' do
expect do
@session.fill_in('Explanation', with: 'Dude', exact: true)
end.to raise_error(Capybara::ElementNotFound)
end
end
it 'should return the element filled in' do
el = @session.find(:fillable_field, 'form_first_name')
expect(@session.fill_in('form_first_name', with: 'Harry')).to eq el
end
it 'should warn if passed what looks like a CSS id selector' do
expect do
@session.fill_in('#form_first_name', with: 'Harry')
end.to raise_error(/you may be passing a CSS selector or XPath expression rather than a locator/)
end
end
| ruby | MIT | b3325b198464b806f07ec2011ceb532d6d5cf4ab | 2026-01-04T15:38:10.098638Z | false |
teamcapybara/capybara | https://github.com/teamcapybara/capybara/blob/b3325b198464b806f07ec2011ceb532d6d5cf4ab/lib/capybara/spec/session/has_link_spec.rb | lib/capybara/spec/session/has_link_spec.rb | # frozen_string_literal: true
Capybara::SpecHelper.spec '#has_link?' do
before do
@session.visit('/with_html')
end
it 'should be true if the given link is on the page' do
expect(@session).to have_link('foo')
expect(@session).to have_link('awesome title')
expect(@session).to have_link('A link', href: '/with_simple_html')
expect(@session).to have_link(:'A link', href: :'/with_simple_html')
expect(@session).to have_link('A link', href: %r{/with_simple_html})
expect(@session).to have_link('labore', target: '_self')
end
it 'should be false if the given link is not on the page' do
expect(@session).not_to have_link('monkey')
expect(@session).not_to have_link('A link', href: '/nonexistent-href')
expect(@session).not_to have_link('A link', href: /nonexistent/)
expect(@session).not_to have_link('labore', target: '_blank')
end
it 'should notify if an invalid locator is specified' do
allow(Capybara::Helpers).to receive(:warn).and_return(nil)
@session.has_link?(@session)
expect(Capybara::Helpers).to have_received(:warn).with(/Called from: .+/)
end
context 'with focused:', requires: [:active_element] do
it 'should be true if the given link is on the page and has focus' do
@session.send_keys(:tab)
expect(@session).to have_link('labore', focused: true)
end
it 'should be false if the given link is on the page and does not have focus' do
expect(@session).to have_link('labore', focused: false)
end
end
it 'should raise an error if an invalid option is passed' do
expect do
expect(@session).to have_link('labore', invalid: true)
end.to raise_error(ArgumentError, 'Invalid option(s) :invalid, should be one of :above, :below, :left_of, :right_of, :near, :count, :minimum, :maximum, :between, :text, :id, :class, :style, :visible, :obscured, :exact, :exact_text, :normalize_ws, :match, :wait, :filter_set, :focused, :href, :alt, :title, :target, :download')
end
end
Capybara::SpecHelper.spec '#has_no_link?' do
before do
@session.visit('/with_html')
end
it 'should be false if the given link is on the page' do
expect(@session).not_to have_no_link('foo')
expect(@session).not_to have_no_link('awesome title')
expect(@session).not_to have_no_link('A link', href: '/with_simple_html')
expect(@session).not_to have_no_link('labore', target: '_self')
end
it 'should be true if the given link is not on the page' do
expect(@session).to have_no_link('monkey')
expect(@session).to have_no_link('A link', href: '/nonexistent-href')
expect(@session).to have_no_link('A link', href: %r{/nonexistent-href})
expect(@session).to have_no_link('labore', target: '_blank')
end
context 'with focused:', requires: [:active_element] do
it 'should be true if the given link is on the page and has focus' do
expect(@session).to have_no_link('labore', focused: true)
end
it 'should be false if the given link is on the page and does not have focus' do
@session.send_keys(:tab)
expect(@session).to have_no_link('labore', focused: 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/spec/session/screenshot_spec.rb | lib/capybara/spec/session/screenshot_spec.rb | # coding: US-ASCII
# frozen_string_literal: true
Capybara::SpecHelper.spec '#save_screenshot' do
let(:image_path) { File.join(Dir.tmpdir, 'capybara-screenshot.png') }
before do
@session.visit '/'
end
it 'should generate PNG file', requires: [:screenshot] do
path = @session.save_screenshot image_path
magic = File.read(image_path, 4)
expect(magic).to eq "\x89PNG"
expect(path).to eq image_path
end
end
| ruby | MIT | b3325b198464b806f07ec2011ceb532d6d5cf4ab | 2026-01-04T15:38:10.098638Z | false |
teamcapybara/capybara | https://github.com/teamcapybara/capybara/blob/b3325b198464b806f07ec2011ceb532d6d5cf4ab/lib/capybara/spec/session/has_text_spec.rb | lib/capybara/spec/session/has_text_spec.rb | # frozen_string_literal: true
Capybara::SpecHelper.spec '#has_text?' do
it 'should be true if the given text is on the page at least once' do
@session.visit('/with_html')
expect(@session).to have_text('est')
expect(@session).to have_text('Lorem')
expect(@session).to have_text('Redirect')
expect(@session).to have_text(:Redirect)
end
it 'should be true if scoped to an element which has the text' do
@session.visit('/with_html')
@session.within("//a[@title='awesome title']") do
expect(@session).to have_text('labore')
end
end
it 'should be false if scoped to an element which does not have the text' do
@session.visit('/with_html')
@session.within("//a[@title='awesome title']") do
expect(@session).not_to have_text('monkey')
end
end
it 'should ignore tags' do
@session.visit('/with_html')
expect(@session).not_to have_text('exercitation <a href="/foo" id="foo">ullamco</a> laboris')
expect(@session).to have_text('exercitation ullamco laboris')
end
it 'should search correctly normalized text' do
@session.visit('/with_html')
expect(@session).to have_text('text with whitespace')
end
it 'should search whitespace collapsed text' do
@session.visit('/with_html')
expect(@session).to have_text('text with whitespace', normalize_ws: true)
end
context 'with enabled default collapsing whitespace' do
before { Capybara.default_normalize_ws = true }
it 'should search unnormalized text' do
@session.visit('/with_html')
expect(@session).to have_text('text with whitespace', normalize_ws: false)
end
it 'should search whitespace collapsed text' do
@session.visit('/with_html')
expect(@session).to have_text('text with whitespace')
end
end
it 'should be false if the given text is not on the page' do
@session.visit('/with_html')
expect(@session).not_to have_text('xxxxyzzz')
expect(@session).not_to have_text('monkey')
end
it 'should handle single quotes in the text' do
@session.visit('/with-quotes')
expect(@session).to have_text("can't")
end
it 'should handle double quotes in the text' do
@session.visit('/with-quotes')
expect(@session).to have_text('"No," he said')
end
it 'should handle mixed single and double quotes in the text' do
@session.visit('/with-quotes')
expect(@session).to have_text(%q("you can't do that."))
end
it 'should be false if text is in the title tag in the head' do
@session.visit('/with_js')
expect(@session).not_to have_text('with_js')
end
it 'should be false if text is inside a script tag in the body' do
@session.visit('/with_js')
expect(@session).not_to have_text('a javascript comment')
expect(@session).not_to have_text('aVar')
end
it 'should be false if the given text is on the page but not visible' do
@session.visit('/with_html')
expect(@session).not_to have_text('Inside element with hidden ancestor')
end
it 'should be true if :all given and text is invisible.' do
@session.visit('/with_html')
expect(@session).to have_text(:all, 'Some of this text is hidden!')
end
it 'should be true if `Capybara.ignore_hidden_elements = false` and text is invisible.' do
Capybara.ignore_hidden_elements = false
@session.visit('/with_html')
expect(@session).to have_text('Some of this text is hidden!')
end
it 'should be true if the text in the page matches given regexp' do
@session.visit('/with_html')
expect(@session).to have_text(/Lorem/)
end
it "should be false if the text in the page doesn't match given regexp" do
@session.visit('/with_html')
expect(@session).not_to have_text(/xxxxyzzz/)
end
context 'with object implementing to_s and to_hash' do
it 'should work if the object is passed alone' do
with_to_hash = Class.new do
def to_s; '42' end
def to_hash; { value: 'Other hash' } end
end.new
@session.visit('/with_html')
expect(@session).to have_text(with_to_hash)
end
it 'should work if passed with empty options' do
with_to_hash = Class.new do
def to_s; '42' end
def to_hash; { value: 'Other hash' } end
end.new
@session.visit('/with_html')
expect(@session).to have_text(:visible, with_to_hash, **{})
end
end
context 'with exact: true option' do
it 'should be true if text matches exactly' do
@session.visit('/with_html')
expect(@session.find(:id, 'h2one')).to have_text('Header Class Test One', exact: true)
end
it "should be false if text doesn't match exactly" do
@session.visit('/with_html')
expect(@session.find(:id, 'h2one')).not_to have_text('Header Class Test On', exact: true)
end
end
it 'should escape any characters that would have special meaning in a regexp' do
@session.visit('/with_html')
expect(@session).not_to have_text('.orem')
end
it 'should accept non-string parameters' do
@session.visit('/with_html')
expect(@session).to have_text(42)
end
it 'should be true when passed nil, and warn about it' do
# nil is converted to '' when to_s is invoked
@session.visit('/with_html')
expect do
expect(@session).to have_text(nil)
end.to output(/Checking for expected text of nil is confusing/).to_stderr
end
it 'should wait for text to appear', requires: [:js] do
Capybara.using_wait_time(3) do
@session.visit('/with_js')
@session.click_link('Click me')
expect(@session).to have_text('Has been clicked')
end
end
context 'with between' do
it 'should be true if the text occurs within the range given' do
@session.visit('/with_count')
expect(@session).to have_text('count', between: 1..3)
expect(@session).to have_text(/count/, between: 2..2)
end
it 'should be false if the text occurs more or fewer times than range' do
@session.visit('/with_count')
expect(@session).not_to have_text('count', between: 0..1)
expect(@session).not_to have_text('count', between: 3..10)
expect(@session).not_to have_text(/count/, between: 2...2)
end
end
context 'with count' do
it 'should be true if the text occurs the given number of times' do
@session.visit('/with_count')
expect(@session).to have_text('count', count: 2)
expect(@session).to have_text('count').exactly(2).times
end
it 'should be false if the text occurs a different number of times than the given' do
@session.visit('/with_count')
expect(@session).not_to have_text('count', count: 0)
expect(@session).not_to have_text('count', count: 1)
expect(@session).not_to have_text('count').once
expect(@session).not_to have_text(/count/, count: 3)
end
it 'should coerce count to an integer' do
@session.visit('/with_count')
expect(@session).to have_text('count', count: '2')
expect(@session).not_to have_text('count', count: '3')
end
end
context 'with maximum' do
it 'should be true when text occurs same or fewer times than given' do
@session.visit('/with_count')
expect(@session).to have_text('count', maximum: 2)
expect(@session).to have_text('count').at_most(2).times
expect(@session).to have_text(/count/, maximum: 3)
end
it 'should be false when text occurs more times than given' do
@session.visit('/with_count')
expect(@session).not_to have_text('count', maximum: 1)
expect(@session).not_to have_text('count').at_most(1).times
expect(@session).not_to have_text('count', maximum: 0)
end
it 'should coerce maximum to an integer' do
@session.visit('/with_count')
expect(@session).to have_text('count', maximum: '2')
expect(@session).not_to have_text('count', maximum: '1')
end
end
context 'with minimum' do
it 'should be true when text occurs same or more times than given' do
@session.visit('/with_count')
expect(@session).to have_text('count', minimum: 2)
expect(@session).to have_text('count').at_least(2).times
expect(@session).to have_text(/count/, minimum: 0)
end
it 'should be false when text occurs fewer times than given' do
@session.visit('/with_count')
expect(@session).not_to have_text('count', minimum: 3)
expect(@session).not_to have_text('count').at_least(3).times
end
it 'should coerce minimum to an integer' do
@session.visit('/with_count')
expect(@session).to have_text('count', minimum: '2')
expect(@session).not_to have_text('count', minimum: '3')
end
end
context 'with wait', requires: [:js] do
it 'should find element if it appears before given wait duration' do
Capybara.using_wait_time(0.1) do
@session.visit('/with_js')
@session.click_link('Click me')
expect(@session).to have_text('Has been clicked', wait: 3)
end
end
end
it 'should raise an error if an invalid option is passed' do
@session.visit('/with_html')
expect do
expect(@session).to have_text('Lorem', invalid: true)
end.to raise_error(ArgumentError)
end
end
Capybara::SpecHelper.spec '#has_no_text?' do
it 'should be false if the given text is on the page at least once' do
@session.visit('/with_html')
expect(@session).not_to have_no_text('est')
expect(@session).not_to have_no_text('Lorem')
expect(@session).not_to have_no_text('Redirect')
end
it 'should be false if scoped to an element which has the text' do
@session.visit('/with_html')
@session.within("//a[@title='awesome title']") do
expect(@session).not_to have_no_text('labore')
end
end
it 'should be true if scoped to an element which does not have the text' do
@session.visit('/with_html')
@session.within("//a[@title='awesome title']") do
expect(@session).to have_no_text('monkey')
end
end
it 'should ignore tags' do
@session.visit('/with_html')
expect(@session).to have_no_text('exercitation <a href="/foo" id="foo">ullamco</a> laboris')
expect(@session).not_to have_no_text('exercitation ullamco laboris')
end
it 'should be true if the given text is not on the page' do
@session.visit('/with_html')
expect(@session).to have_no_text('xxxxyzzz')
expect(@session).to have_no_text('monkey')
end
it 'should handle single quotes in the text' do
@session.visit('/with-quotes')
expect(@session).not_to have_no_text("can't")
end
it 'should handle double quotes in the text' do
@session.visit('/with-quotes')
expect(@session).not_to have_no_text('"No," he said')
end
it 'should handle mixed single and double quotes in the text' do
@session.visit('/with-quotes')
expect(@session).not_to have_no_text(%q("you can't do that."))
end
it 'should be true if text is in the title tag in the head' do
@session.visit('/with_js')
expect(@session).to have_no_text('with_js')
end
it 'should be true if text is inside a script tag in the body' do
@session.visit('/with_js')
expect(@session).to have_no_text('a javascript comment')
expect(@session).to have_no_text('aVar')
end
it 'should be true if the given text is on the page but not visible' do
@session.visit('/with_html')
expect(@session).to have_no_text('Inside element with hidden ancestor')
end
it 'should be false if :all given and text is invisible.' do
@session.visit('/with_html')
expect(@session).not_to have_no_text(:all, 'Some of this text is hidden!')
end
it 'should be false if `Capybara.ignore_hidden_elements = false` and text is invisible.' do
Capybara.ignore_hidden_elements = false
@session.visit('/with_html')
expect(@session).not_to have_no_text('Some of this text is hidden!')
end
it "should be true if the text in the page doesn't match given regexp" do
@session.visit('/with_html')
expect(@session).to have_no_text(/xxxxyzzz/)
end
it 'should be false if the text in the page matches given regexp' do
@session.visit('/with_html')
expect(@session).not_to have_no_text(/Lorem/)
end
it 'should escape any characters that would have special meaning in a regexp' do
@session.visit('/with_html')
expect(@session).to have_no_text('.orem')
end
it 'should wait for text to disappear', requires: [:js] do
Capybara.default_max_wait_time = 2
@session.visit('/with_js')
@session.click_link('Click me')
expect(@session).to have_no_text('I changed it')
end
context 'with wait', requires: [:js] do
it 'should not find element if it appears after given wait duration' do
@session.visit('/with_js')
@session.click_link('Click me')
expect(@session).to have_no_text('Has been clicked', wait: 0.05)
end
end
end
| ruby | MIT | b3325b198464b806f07ec2011ceb532d6d5cf4ab | 2026-01-04T15:38:10.098638Z | false |
teamcapybara/capybara | https://github.com/teamcapybara/capybara/blob/b3325b198464b806f07ec2011ceb532d6d5cf4ab/lib/capybara/spec/session/ancestor_spec.rb | lib/capybara/spec/session/ancestor_spec.rb | # frozen_string_literal: true
Capybara::SpecHelper.spec '#ancestor' do
before do
@session.visit('/with_html')
end
after do
Capybara::Selector.remove(:monkey)
end
it 'should find the ancestor element using the given locator' do
el = @session.find(:css, '#first_image')
expect(el.ancestor('//p')).to have_text('Lorem ipsum dolor')
expect(el.ancestor('//a')[:'aria-label']).to eq('Go to simple')
end
it 'should find the ancestor element using the given locator and options' do
el = @session.find(:css, '#child')
expect(el.ancestor('//div', text: "Ancestor\nAncestor\nAncestor")[:id]).to eq('ancestor3')
end
it 'should find the closest ancestor' do
el = @session.find(:css, '#child')
expect(el.ancestor('.//div', order: :reverse, match: :first)[:id]).to eq('ancestor1')
end
it 'should raise an error if there are multiple matches' do
el = @session.find(:css, '#child')
expect { el.ancestor('//div') }.to raise_error(Capybara::Ambiguous)
expect { el.ancestor('//div', text: 'Ancestor') }.to raise_error(Capybara::Ambiguous)
end
context 'with css selectors' do
it 'should find the first element using the given locator' do
el = @session.find(:css, '#first_image')
expect(el.ancestor(:css, 'p')).to have_text('Lorem ipsum dolor')
expect(el.ancestor(:css, 'a')[:'aria-label']).to eq('Go to simple')
end
it 'should support pseudo selectors' do
el = @session.find(:css, '#button_img')
expect(el.ancestor(:css, 'button:disabled')[:id]).to eq('ancestor_button')
end
end
context 'with xpath selectors' do
it 'should find the first element using the given locator' do
el = @session.find(:css, '#first_image')
expect(el.ancestor(:xpath, '//p')).to have_text('Lorem ipsum dolor')
expect(el.ancestor(:xpath, '//a')[:'aria-label']).to eq('Go to simple')
end
end
context 'with custom selector' do
it 'should use the custom selector' do
Capybara.add_selector(:level) do
xpath { |num| ".//*[@id='ancestor#{num}']" }
end
el = @session.find(:css, '#child')
expect(el.ancestor(:level, 1)[:id]).to eq 'ancestor1'
expect(el.ancestor(:level, 3)[:id]).to eq 'ancestor3'
end
end
it 'should raise ElementNotFound with a useful default message if nothing was found' do
el = @session.find(:css, '#child')
expect do
el.ancestor(:xpath, '//div[@id="nosuchthing"]')
end.to raise_error(Capybara::ElementNotFound, 'Unable to find xpath "//div[@id=\\"nosuchthing\\"]" that is an ancestor of visible css "#child"')
end
context 'within a scope' do
it 'should limit the ancestors to inside the scope' do
@session.within(:css, '#ancestor2') do
el = @session.find(:css, '#child')
expect(el.ancestor(:css, 'div', text: 'Ancestor')[:id]).to eq('ancestor1')
end
end
end
it 'should raise if selector type is unknown' do
el = @session.find(:css, '#child')
expect do
el.ancestor(:unknown, '//h1')
end.to raise_error(ArgumentError)
end
end
| ruby | MIT | b3325b198464b806f07ec2011ceb532d6d5cf4ab | 2026-01-04T15:38:10.098638Z | false |
teamcapybara/capybara | https://github.com/teamcapybara/capybara/blob/b3325b198464b806f07ec2011ceb532d6d5cf4ab/lib/capybara/spec/session/title_spec.rb | lib/capybara/spec/session/title_spec.rb | # frozen_string_literal: true
Capybara::SpecHelper.spec '#title' do
it 'should get the title of the page' do
@session.visit('/with_title')
expect(@session.title).to eq('Test Title')
end
context 'with css as default selector' do
before { Capybara.default_selector = :css }
after { Capybara.default_selector = :xpath }
it 'should get the title of the page' do
@session.visit('/with_title')
expect(@session.title).to eq('Test Title')
end
end
context 'within iframe', requires: [:frames] do
it 'should get the title of the top level browsing context' do
@session.visit('/within_frames')
expect(@session.title).to eq('With Frames')
@session.within_frame('frameOne') do
expect(@session.title).to eq('With Frames')
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/spec/session/node_wrapper_spec.rb | lib/capybara/spec/session/node_wrapper_spec.rb | # frozen_string_literal: true
class NodeWrapper
def initialize(element); @element = element end
def to_capybara_node(); @element end
end
Capybara::SpecHelper.spec '#to_capybara_node' do
before do
@session.visit('/with_html')
end
it 'should support have_xxx expectations' do
para = NodeWrapper.new(@session.find(:css, '#first'))
expect(para).to have_link('ullamco')
end
it 'should support within' do
para = NodeWrapper.new(@session.find(:css, '#first'))
expect(@session).to have_css('#second')
@session.within(para) do
expect(@session).to have_link('ullamco')
expect(@session).not_to have_css('#second')
end
end
it 'should generate correct errors' do
para = NodeWrapper.new(@session.find(:css, '#first'))
expect do
expect(para).to have_text('Header Class Test One')
end.to raise_error(/^expected to find text "Header Class Test One" in "Lore/)
expect do
expect(para).to have_css('#second')
end.to raise_error(/^expected to find css "#second" within #<Capybara::Node::Element/)
expect do
expect(para).to have_link(href: %r{/without_simple_html})
end.to raise_error(%r{^expected to find link with href matching /\\/without_simple_html/ within #<Capybara::Node::Element})
end
end
| ruby | MIT | b3325b198464b806f07ec2011ceb532d6d5cf4ab | 2026-01-04T15:38:10.098638Z | false |
teamcapybara/capybara | https://github.com/teamcapybara/capybara/blob/b3325b198464b806f07ec2011ceb532d6d5cf4ab/lib/capybara/spec/session/headers_spec.rb | lib/capybara/spec/session/headers_spec.rb | # frozen_string_literal: true
Capybara::SpecHelper.spec '#response_headers' do
it 'should return response headers', requires: [:response_headers] do
@session.visit('/with_simple_html')
expect(@session.response_headers['Content-Type']).to match %r{text/html}
end
end
| ruby | MIT | b3325b198464b806f07ec2011ceb532d6d5cf4ab | 2026-01-04T15:38:10.098638Z | false |
teamcapybara/capybara | https://github.com/teamcapybara/capybara/blob/b3325b198464b806f07ec2011ceb532d6d5cf4ab/lib/capybara/spec/session/visit_spec.rb | lib/capybara/spec/session/visit_spec.rb | # frozen_string_literal: true
Capybara::SpecHelper.spec '#visit' do
it 'should fetch a response from the driver with a relative url' do
@session.visit('/')
expect(@session).to have_content('Hello world!')
@session.visit('/foo')
expect(@session).to have_content('Another World')
end
it 'should fetch a response from the driver with an absolute url with a port' do
# Preparation
@session.visit('/')
root_uri = URI.parse(@session.current_url)
@session.visit("http://#{root_uri.host}:#{root_uri.port}/")
expect(@session).to have_content('Hello world!')
@session.visit("http://#{root_uri.host}:#{root_uri.port}/foo")
expect(@session).to have_content('Another World')
end
it "should fetch a response when absolute URI doesn't have a trailing slash" do
# Preparation
@session.visit('/foo/bar')
root_uri = URI.parse(@session.current_url)
@session.visit("http://#{root_uri.host}:#{root_uri.port}")
expect(@session).to have_content('Hello world!')
end
it 'should fetch a response when sequentially visiting same destination with a target' do
@session.visit('/form')
expect(@session).to have_css('#form_title')
@session.visit('/form#form_title')
expect(@session).to have_css('#form_title')
end
it 'raises any errors caught inside the server', requires: [:server] do
quietly { @session.visit('/error') }
expect do
@session.visit('/')
end.to raise_error(TestApp::TestAppError)
end
it 'should be able to open non-http url', requires: [:about_scheme] do
@session.visit('about:blank')
@session.assert_no_selector :xpath, '/html/body/*'
end
context 'when Capybara.always_include_port is true' do
let(:root_uri) do
@session.visit('/')
URI.parse(@session.current_url)
end
before do
Capybara.always_include_port = true
end
after do
Capybara.always_include_port = false
end
it 'should fetch a response from the driver with an absolute url without a port' do
@session.visit("http://#{root_uri.host}/")
expect(URI.parse(@session.current_url).port).to eq(root_uri.port)
expect(@session).to have_content('Hello world!')
@session.visit("http://#{root_uri.host}/foo")
expect(URI.parse(@session.current_url).port).to eq(root_uri.port)
expect(@session).to have_content('Another World')
end
it 'should add the server port to a visited url if no port specified', requires: [:server] do
allow(@session.driver).to receive(:visit)
@session.visit('http://www.example.com')
expect(@session.driver).to have_received(:visit).with("http://www.example.com:#{@session.server.port}")
end
it 'should not override the visit specified port even if default for scheme', requires: [:server] do
allow(@session.driver).to receive(:visit)
@session.visit('http://www.example.com:80')
expect(@session.driver).to have_received(:visit).with('http://www.example.com:80')
end
it 'should give preference to app_host port if specified', requires: [:server] do
allow(@session.driver).to receive(:visit)
Capybara.app_host = 'http://www.example.com:6666'
@session.visit('/random')
expect(@session.driver).to have_received(:visit).with('http://www.example.com:6666/random')
end
it "shouldn't override port if no server", requires: [:server] do
session = Capybara::Session.new(@session.mode, nil)
allow(session.driver).to receive(:visit)
session.visit('http://www.google.com')
expect(session.driver).to have_received(:visit).with('http://www.google.com')
end
it "shouldn't override port if no server but app_host is set", requires: [:server] do
session = Capybara::Session.new(@session.mode, nil)
Capybara.app_host = 'http://www.example.com:6666'
allow(session.driver).to receive(:visit)
session.visit('http://www.google.com')
expect(session.driver).to have_received(:visit).with('http://www.google.com')
end
end
context 'when Capybara.always_include_port is false' do
before do
Capybara.always_include_port = false
end
it "shouldn't overwrite port if app_host is set", requires: [:server] do
session = Capybara::Session.new(@session.mode, nil)
Capybara.app_host = 'http://www.example.com:6666'
allow(session.driver).to receive(:visit)
session.visit('http://www.google.com')
expect(session.driver).to have_received(:visit).with('http://www.google.com')
end
it "shouldn't overwrite port if port specfified", requires: [:server] do
session = Capybara::Session.new(@session.mode, nil)
Capybara.app_host = 'http://www.example.com:6666'
allow(session.driver).to receive(:visit)
session.visit('http://www.google.com:99')
expect(session.driver).to have_received(:visit).with('http://www.google.com:99')
end
end
context 'without a server', requires: [:server] do
it 'should respect `app_host`' do
serverless_session = Capybara::Session.new(@session.mode, nil)
Capybara.app_host = "http://#{@session.server.host}:#{@session.server.port}"
serverless_session.visit('/foo')
expect(serverless_session).to have_content('Another World')
end
it 'should visit a fully qualified URL' do
serverless_session = Capybara::Session.new(@session.mode, nil)
serverless_session.visit("http://#{@session.server.host}:#{@session.server.port}/foo")
expect(serverless_session).to have_content('Another World')
end
end
context 'with Capybara.app_host set' do
it 'should override server', requires: [:server] do
another_session = Capybara::Session.new(@session.mode, @session.app.dup)
Capybara.app_host = "http://#{@session.server.host}:#{@session.server.port}"
another_session.visit('/foo')
expect(another_session).to have_content('Another World')
expect(another_session.current_url).to start_with(Capybara.app_host)
expect(URI.parse(another_session.current_url).port).not_to eq another_session.server.port
expect(URI.parse(another_session.current_url).port).to eq @session.server.port
end
it 'should append relative path', requires: [:server] do
Capybara.app_host = "http://#{@session.server.host}:#{@session.server.port}/redirect/0"
@session.visit('/times')
expect(@session).to have_content('redirection complete')
end
it 'should work if `app_host` has a trailing /', requires: [:server] do
Capybara.app_host = "http://#{@session.server.host}:#{@session.server.port}/"
@session.visit('/')
expect(@session).to have_content('Hello world!')
end
end
it 'should send no referer when visiting a page' do
@session.visit '/get_referer'
expect(@session).to have_content 'No referer'
end
it 'should send no referer when visiting a second page' do
@session.visit '/get_referer'
@session.visit '/get_referer'
expect(@session).to have_content 'No referer'
end
it 'should send a referer when following a link' do
@session.visit '/referer_base'
@session.find('//a[@href="/get_referer"]').click
expect(@session).to have_content %r{http://.*/referer_base}
end
it 'should preserve the original referer URL when following a redirect' do
@session.visit('/referer_base')
@session.find('//a[@href="/redirect_to_get_referer"]').click
expect(@session).to have_content %r{http://.*/referer_base}
end
it 'should send a referer when submitting a form' do
@session.visit '/referer_base'
@session.find('//input').click
expect(@session).to have_content %r{http://.*/referer_base}
end
it 'can set cookie if a blank path is specified' do
@session.visit('')
@session.visit('/get_cookie')
expect(@session).to have_content('root cookie')
end
context 'with base element' do
it 'should use base href with relative links' do
@session.visit('/base/with_base')
@session.click_link('Title page')
expect(@session).to have_current_path('/with_title')
end
it 'should use base href with bare queries' do
@session.visit('/base/with_base')
@session.click_link('Bare query')
expect(@session).to have_current_path('/?a=3')
end
it 'should not use the base href with a new visit call' do
@session.visit('/base/with_other_base')
@session.visit('with_html')
expect(@session).to have_current_path('/with_html')
end
end
end
| ruby | MIT | b3325b198464b806f07ec2011ceb532d6d5cf4ab | 2026-01-04T15:38:10.098638Z | false |
teamcapybara/capybara | https://github.com/teamcapybara/capybara/blob/b3325b198464b806f07ec2011ceb532d6d5cf4ab/lib/capybara/spec/session/body_spec.rb | lib/capybara/spec/session/body_spec.rb | # frozen_string_literal: true
Capybara::SpecHelper.spec '#body' do
it 'should return the unmodified page body' do
@session.visit('/')
expect(@session).to have_content('Hello world!') # wait for content to appear if visit is async
expect(@session.body).to include('Hello world!')
end
context 'encoding of response between ascii and utf8' do
it 'should be valid with html entities' do
@session.visit('/with_html_entities')
expect(@session).to have_content('Encoding') # wait for content to appear if visit is async
expect { @session.body.encode!('UTF-8') }.not_to raise_error
end
it 'should be valid without html entities' do
@session.visit('/with_html')
expect(@session).to have_content('This is a test') # wait for content to appear if visit is async
expect { @session.body.encode!('UTF-8') }.not_to raise_error
end
end
end
| ruby | MIT | b3325b198464b806f07ec2011ceb532d6d5cf4ab | 2026-01-04T15:38:10.098638Z | false |
teamcapybara/capybara | https://github.com/teamcapybara/capybara/blob/b3325b198464b806f07ec2011ceb532d6d5cf4ab/lib/capybara/spec/session/save_page_spec.rb | lib/capybara/spec/session/save_page_spec.rb | # frozen_string_literal: true
Capybara::SpecHelper.spec '#save_page' do
let(:alternative_path) { File.join(Dir.pwd, 'save_and_open_page_tmp') }
before do
@old_save_path = Capybara.save_path
Capybara.save_path = nil
@session.visit('/foo')
end
after do
Capybara.save_path = @old_save_path
Dir.glob('capybara-*.html').each do |file|
FileUtils.rm(file)
end
FileUtils.rm_rf alternative_path
end
it 'saves the page in the root directory' do
@session.save_page
path = Dir.glob('capybara-*.html').first
expect(File.read(path)).to include('Another World')
end
it 'generates a sensible filename' do
@session.save_page
filename = Dir.glob('capybara-*.html').first
expect(filename).to match(/^capybara-\d+\.html$/)
end
it 'can store files in a specified directory' do
Capybara.save_path = alternative_path
@session.save_page
path = Dir.glob("#{alternative_path}/capybara-*.html").first
expect(File.read(path)).to include('Another World')
end
it 'uses the given filename' do
@session.save_page('capybara-001122.html')
expect(File.read('capybara-001122.html')).to include('Another World')
end
it 'can store files in a specified directory with a given filename' do
Capybara.save_path = alternative_path
@session.save_page('capybara-001133.html')
path = "#{alternative_path}/capybara-001133.html"
expect(File.read(path)).to include('Another World')
end
it 'can store files in a specified directory with a given relative filename' do
Capybara.save_path = alternative_path
@session.save_page('tmp/capybara-001144.html')
path = "#{alternative_path}/tmp/capybara-001144.html"
expect(File.read(path)).to include('Another World')
end
it 'returns an absolute path in pwd' do
result = @session.save_page
path = File.expand_path(Dir.glob('capybara-*.html').first, Dir.pwd)
expect(result).to eq(path)
end
it 'returns an absolute path in given directory' do
Capybara.save_path = alternative_path
result = @session.save_page
path = File.expand_path(Dir.glob("#{alternative_path}/capybara-*.html").first, alternative_path)
expect(result).to eq(path)
end
context 'asset_host contains a string' do
before { Capybara.asset_host = 'http://example.com' }
after { Capybara.asset_host = nil }
it 'prepends base tag with value from asset_host to the head' do
@session.visit('/with_js')
path = @session.save_page
result = File.read(path)
expect(result).to include("<head><base href='http://example.com' />")
end
it "doesn't prepend base tag to pages when asset_host is nil" do
Capybara.asset_host = nil
@session.visit('/with_js')
path = @session.save_page
result = File.read(path)
expect(result).to include('<html')
expect(result).not_to include('http://example.com')
end
it "doesn't prepend base tag to pages which already have it" do
@session.visit('/with_base_tag')
path = @session.save_page
result = File.read(path)
expect(result).to include('<html')
expect(result).not_to include('http://example.com')
end
it 'executes successfully even if the page is missing a <head>' do
@session.visit('/with_simple_html')
path = @session.save_page
result = File.read(path)
expect(result).to include('Bar')
end
end
end
| ruby | MIT | b3325b198464b806f07ec2011ceb532d6d5cf4ab | 2026-01-04T15:38:10.098638Z | false |
teamcapybara/capybara | https://github.com/teamcapybara/capybara/blob/b3325b198464b806f07ec2011ceb532d6d5cf4ab/lib/capybara/spec/session/refresh_spec.rb | lib/capybara/spec/session/refresh_spec.rb | # frozen_string_literal: true
# NOTE: This file uses `sleep` to sync up parts of the tests. This is only implemented like this
# because of the methods being tested. In tests using Capybara this type of behavior should be implemented
# using Capybara provided assertions with builtin waiting behavior.
Capybara::SpecHelper.spec '#refresh' do
it 'reload the page' do
@session.visit('/form')
expect(@session).to have_select('form_locale', selected: 'English')
@session.select('Swedish', from: 'form_locale')
expect(@session).to have_select('form_locale', selected: 'Swedish')
@session.refresh
expect(@session).to have_select('form_locale', selected: 'English')
end
it 'raises any errors caught inside the server', requires: [:server] do
quietly { @session.visit('/error') }
expect do
@session.refresh
end.to raise_error(TestApp::TestAppError)
end
it 'it reposts' do
@session.visit('/form')
@session.select('Sweden', from: 'form_region')
@session.click_button('awesome')
sleep 2
expect do
@session.refresh
sleep 2
end.to change { extract_results(@session)['post_count'] }.by(1)
end
end
| ruby | MIT | b3325b198464b806f07ec2011ceb532d6d5cf4ab | 2026-01-04T15:38:10.098638Z | false |
teamcapybara/capybara | https://github.com/teamcapybara/capybara/blob/b3325b198464b806f07ec2011ceb532d6d5cf4ab/lib/capybara/spec/session/find_spec.rb | lib/capybara/spec/session/find_spec.rb | # frozen_string_literal: true
Capybara::SpecHelper.spec '#find' do
before do
@session.visit('/with_html')
end
after do
Capybara::Selector.remove(:monkey)
end
it 'should find the first element using the given locator' do
expect(@session.find('//h1').text).to eq('This is a test')
expect(@session.find("//input[@id='test_field']").value).to eq('monkey')
end
it 'should find the first element using the given locator and options' do
expect(@session.find('//a', text: 'Redirect')[:id]).to eq('red')
expect(@session.find(:css, 'a', text: 'A link came first')[:title]).to eq('twas a fine link')
end
it 'should raise an error if there are multiple matches' do
expect { @session.find('//a') }.to raise_error(Capybara::Ambiguous)
end
it 'should wait for asynchronous load', requires: [:js] do
Capybara.default_max_wait_time = 2
@session.visit('/with_js')
@session.click_link('Click me')
expect(@session.find(:css, 'a#has-been-clicked').text).to include('Has been clicked')
end
context 'with :text option' do
it "casts text's argument to string" do
expect(@session.find(:css, '.number', text: 42)).to have_content('42')
end
end
context 'with :wait option', requires: [:js] do
it 'should not wait for asynchronous load when `false` given' do
@session.visit('/with_js')
@session.click_link('Click me')
expect do
@session.find(:css, 'a#has-been-clicked', wait: false)
end.to raise_error(Capybara::ElementNotFound)
end
it 'should not find element if it appears after given wait duration' do
@session.visit('/with_js')
@session.click_link('Slowly')
expect do
@session.find(:css, 'a#slow-clicked', wait: 0.2)
end.to raise_error(Capybara::ElementNotFound)
end
it 'should find element if it appears before given wait duration' do
@session.visit('/with_js')
@session.click_link('Click me')
expect(@session.find(:css, 'a#has-been-clicked', wait: 3.0).text).to include('Has been clicked')
end
end
context 'with frozen time', requires: [:js] do
if defined?(Process::CLOCK_MONOTONIC)
it 'will time out even if time is frozen' do
@session.visit('/with_js')
now = Time.now
allow(Time).to receive(:now).and_return(now)
expect { @session.find('//isnotthere') }.to raise_error(Capybara::ElementNotFound)
end
else
it 'raises an error suggesting that Capybara is stuck in time' do
@session.visit('/with_js')
now = Time.now
allow(Time).to receive(:now).and_return(now)
expect { @session.find('//isnotthere') }.to raise_error(Capybara::FrozenInTime)
end
end
end
context 'with css selectors' do
it 'should find the first element using the given locator' do
expect(@session.find(:css, 'h1').text).to eq('This is a test')
expect(@session.find(:css, "input[id='test_field']").value).to eq('monkey')
end
it 'should support pseudo selectors' do
expect(@session.find(:css, 'input:disabled').value).to eq('This is disabled')
end
it 'should support escaping characters' do
expect(@session.find(:css, '#\31 escape\.me').text).to eq('needs escaping')
expect(@session.find(:css, '.\32 escape').text).to eq('needs escaping')
end
it 'should not warn about locator' do
expect { @session.find(:css, '#not_on_page') }.to raise_error Capybara::ElementNotFound do |e|
expect(e.message).not_to match(/you may be passing a CSS selector or XPath expression/)
end
end
end
context 'with xpath selectors' do
it 'should find the first element using the given locator' do
expect(@session.find(:xpath, '//h1').text).to eq('This is a test')
expect(@session.find(:xpath, "//input[@id='test_field']").value).to eq('monkey')
end
it 'should warn if passed a non-valid locator type' do
expect { @session.find(:xpath, 123) }.to raise_error(Exception) # The exact error is not yet well defined
.and output(/must respond to to_xpath or be an instance of String/).to_stderr
end
end
context 'with custom selector' do
it 'should use the custom selector' do
Capybara.add_selector(:beatle) do
xpath { |name| ".//*[@id='#{name}']" }
end
expect(@session.find(:beatle, 'john').text).to eq('John')
expect(@session.find(:beatle, 'paul').text).to eq('Paul')
end
end
context 'with custom selector with custom `match` block' do
it 'should use the custom selector when locator matches the block' do
Capybara.add_selector(:beatle) do
xpath { |num| ".//*[contains(@class, 'beatle')][#{num}]" }
match { |value| value.is_a?(Integer) }
end
expect(@session.find(:beatle, '2').text).to eq('Paul')
expect(@session.find(1).text).to eq('John')
expect(@session.find(2).text).to eq('Paul')
expect(@session.find('//h1').text).to eq('This is a test')
end
end
context 'with custom selector with custom filter' do
before do
Capybara.add_selector(:beatle) do
xpath { |name| ".//li[contains(@class, 'beatle')][contains(text(), '#{name}')]" }
node_filter(:type) { |node, type| node[:class].split(/\s+/).include?(type) }
node_filter(:fail) { |_node, _val| raise Capybara::ElementNotFound, 'fail' }
end
end
it 'should find elements that match the filter' do
expect(@session.find(:beatle, 'Paul', type: 'drummer').text).to eq('Paul')
expect(@session.find(:beatle, 'Ringo', type: 'drummer').text).to eq('Ringo')
end
it 'ignores filter when it is not given' do
expect(@session.find(:beatle, 'Paul').text).to eq('Paul')
expect(@session.find(:beatle, 'John').text).to eq('John')
end
it "should not find elements that don't match the filter" do
expect { @session.find(:beatle, 'John', type: 'drummer') }.to raise_error(Capybara::ElementNotFound)
expect { @session.find(:beatle, 'George', type: 'drummer') }.to raise_error(Capybara::ElementNotFound)
end
it 'should not raise an ElementNotFound error from in a filter' do
expect { @session.find(:beatle, 'John', fail: 'something') }.to raise_error(Capybara::ElementNotFound, /beatle "John"/)
end
end
context 'with custom selector with custom filter and default' do
before do
Capybara.add_selector(:beatle) do
xpath { |name| ".//li[contains(@class, 'beatle')][contains(text(), '#{name}')]" }
node_filter(:type, default: 'drummer') { |node, type| node[:class].split(/\s+/).include?(type) }
end
end
it 'should find elements that match the filter' do
expect(@session.find(:beatle, 'Paul', type: 'drummer').text).to eq('Paul')
expect(@session.find(:beatle, 'Ringo', type: 'drummer').text).to eq('Ringo')
end
it 'should use default value when filter is not given' do
expect(@session.find(:beatle, 'Paul').text).to eq('Paul')
expect { @session.find(:beatle, 'John') }.to raise_error(Capybara::ElementNotFound)
end
it "should not find elements that don't match the filter" do
expect { @session.find(:beatle, 'John', type: 'drummer') }.to raise_error(Capybara::ElementNotFound)
expect { @session.find(:beatle, 'George', type: 'drummer') }.to raise_error(Capybara::ElementNotFound)
end
end
context 'with alternate filter set' do
before do
Capybara::Selector::FilterSet.add(:value) do
node_filter(:with) { |node, with| node.value == with.to_s }
end
Capybara.add_selector(:id_with_field_filters) do
xpath { |id| XPath.descendant[XPath.attr(:id) == id.to_s] }
filter_set(:field)
end
end
it 'should allow use of filters from custom filter set' do
expect(@session.find(:id, 'test_field', filter_set: :value, with: 'monkey').value).to eq('monkey')
expect { @session.find(:id, 'test_field', filter_set: :value, with: 'not_monkey') }.to raise_error(Capybara::ElementNotFound)
end
it 'should allow use of filter set from a different selector' do
expect(@session.find(:id, 'test_field', filter_set: :field, with: 'monkey').value).to eq('monkey')
expect { @session.find(:id, 'test_field', filter_set: :field, with: 'not_monkey') }.to raise_error(Capybara::ElementNotFound)
end
it 'should allow importing of filter set into selector' do
expect(@session.find(:id_with_field_filters, 'test_field', with: 'monkey').value).to eq('monkey')
expect { @session.find(:id_with_field_filters, 'test_field', with: 'not_monkey') }.to raise_error(Capybara::ElementNotFound)
end
end
context 'with css as default selector' do
before { Capybara.default_selector = :css }
after { Capybara.default_selector = :xpath }
it 'should find the first element using the given locator' do
expect(@session.find('h1').text).to eq('This is a test')
expect(@session.find("input[id='test_field']").value).to eq('monkey')
end
end
it 'should raise ElementNotFound with a useful default message if nothing was found' do
expect do
@session.find(:xpath, '//div[@id="nosuchthing"]').to be_nil
end.to raise_error(Capybara::ElementNotFound, 'Unable to find xpath "//div[@id=\\"nosuchthing\\"]"')
end
context 'without locator' do
it 'should not output `nil` in the ElementNotFound message if nothing was found' do
expect do
@session.find(:label, text: 'no such thing').to be_nil
end.to raise_error(Capybara::ElementNotFound, 'Unable to find label')
end
end
it 'should accept an XPath instance' do
@session.visit('/form')
@xpath = Capybara::Selector.new(:fillable_field, config: {}, format: :xpath).call('First Name')
expect(@xpath).to be_a(XPath::Union)
expect(@session.find(@xpath).value).to eq('John')
end
context 'with :exact option' do
it 'matches exactly when true' do
expect(@session.find(:xpath, XPath.descendant(:input)[XPath.attr(:id).is('test_field')], exact: true).value).to eq('monkey')
expect do
@session.find(:xpath, XPath.descendant(:input)[XPath.attr(:id).is('est_fiel')], exact: true)
end.to raise_error(Capybara::ElementNotFound)
end
it 'matches loosely when false' do
expect(@session.find(:xpath, XPath.descendant(:input)[XPath.attr(:id).is('test_field')], exact: false).value).to eq('monkey')
expect(@session.find(:xpath, XPath.descendant(:input)[XPath.attr(:id).is('est_fiel')], exact: false).value).to eq('monkey')
end
it 'defaults to `Capybara.exact`' do
Capybara.exact = true
expect do
@session.find(:xpath, XPath.descendant(:input)[XPath.attr(:id).is('est_fiel')])
end.to raise_error(Capybara::ElementNotFound)
Capybara.exact = false
@session.find(:xpath, XPath.descendant(:input)[XPath.attr(:id).is('est_fiel')])
end
it 'warns when the option has no effect' do
expect { @session.find(:css, '#test_field', exact: true) }.to \
output(/^The :exact option only has an effect on queries using the XPath#is method. Using it with the query "#test_field" has no effect/).to_stderr
end
end
context 'with :match option' do
context 'when set to `one`' do
it 'raises an error when multiple matches exist' do
expect do
@session.find(:css, '.multiple', match: :one)
end.to raise_error(Capybara::Ambiguous)
end
it 'raises an error even if there the match is exact and the others are inexact' do
expect do
@session.find(:xpath, XPath.descendant[XPath.attr(:class).is('almost_singular')], exact: false, match: :one)
end.to raise_error(Capybara::Ambiguous)
end
it 'returns the element if there is only one' do
expect(@session.find(:css, '.singular', match: :one).text).to eq('singular')
end
it 'raises an error if there is no match' do
expect do
@session.find(:css, '.does-not-exist', match: :one)
end.to raise_error(Capybara::ElementNotFound)
end
end
context 'when set to `first`' do
it 'returns the first matched element' do
expect(@session.find(:css, '.multiple', match: :first).text).to eq('multiple one')
end
it 'raises an error if there is no match' do
expect do
@session.find(:css, '.does-not-exist', match: :first)
end.to raise_error(Capybara::ElementNotFound)
end
end
context 'when set to `smart`' do
context 'and `exact` set to `false`' do
it 'raises an error when there are multiple exact matches' do
expect do
@session.find(:xpath, XPath.descendant[XPath.attr(:class).is('multiple')], match: :smart, exact: false)
end.to raise_error(Capybara::Ambiguous)
end
it 'finds a single exact match when there also are inexact matches' do
result = @session.find(:xpath, XPath.descendant[XPath.attr(:class).is('almost_singular')], match: :smart, exact: false)
expect(result.text).to eq('almost singular')
end
it 'raises an error when there are multiple inexact matches' do
expect do
@session.find(:xpath, XPath.descendant[XPath.attr(:class).is('almost_singul')], match: :smart, exact: false)
end.to raise_error(Capybara::Ambiguous)
end
it 'finds a single inexact match' do
result = @session.find(:xpath, XPath.descendant[XPath.attr(:class).is('almost_singular but')], match: :smart, exact: false)
expect(result.text).to eq('almost singular but not quite')
end
it 'raises an error if there is no match' do
expect do
@session.find(:xpath, XPath.descendant[XPath.attr(:class).is('does-not-exist')], match: :smart, exact: false)
end.to raise_error(Capybara::ElementNotFound)
end
end
context 'with `exact` set to `true`' do
it 'raises an error when there are multiple exact matches' do
expect do
@session.find(:xpath, XPath.descendant[XPath.attr(:class).is('multiple')], match: :smart, exact: true)
end.to raise_error(Capybara::Ambiguous)
end
it 'finds a single exact match when there also are inexact matches' do
result = @session.find(:xpath, XPath.descendant[XPath.attr(:class).is('almost_singular')], match: :smart, exact: true)
expect(result.text).to eq('almost singular')
end
it 'raises an error when there are multiple inexact matches' do
expect do
@session.find(:xpath, XPath.descendant[XPath.attr(:class).is('almost_singul')], match: :smart, exact: true)
end.to raise_error(Capybara::ElementNotFound)
end
it 'raises an error when there is a single inexact matches' do
expect do
@session.find(:xpath, XPath.descendant[XPath.attr(:class).is('almost_singular but')], match: :smart, exact: true)
end.to raise_error(Capybara::ElementNotFound)
end
it 'raises an error if there is no match' do
expect do
@session.find(:xpath, XPath.descendant[XPath.attr(:class).is('does-not-exist')], match: :smart, exact: true)
end.to raise_error(Capybara::ElementNotFound)
end
end
end
context 'when set to `prefer_exact`' do
context 'and `exact` set to `false`' do
it 'picks the first one when there are multiple exact matches' do
result = @session.find(:xpath, XPath.descendant[XPath.attr(:class).is('multiple')], match: :prefer_exact, exact: false)
expect(result.text).to eq('multiple one')
end
it 'finds a single exact match when there also are inexact matches' do
result = @session.find(:xpath, XPath.descendant[XPath.attr(:class).is('almost_singular')], match: :prefer_exact, exact: false)
expect(result.text).to eq('almost singular')
end
it 'picks the first one when there are multiple inexact matches' do
result = @session.find(:xpath, XPath.descendant[XPath.attr(:class).is('almost_singul')], match: :prefer_exact, exact: false)
expect(result.text).to eq('almost singular but not quite')
end
it 'finds a single inexact match' do
result = @session.find(:xpath, XPath.descendant[XPath.attr(:class).is('almost_singular but')], match: :prefer_exact, exact: false)
expect(result.text).to eq('almost singular but not quite')
end
it 'raises an error if there is no match' do
expect do
@session.find(:xpath, XPath.descendant[XPath.attr(:class).is('does-not-exist')], match: :prefer_exact, exact: false)
end.to raise_error(Capybara::ElementNotFound)
end
end
context 'with `exact` set to `true`' do
it 'picks the first one when there are multiple exact matches' do
result = @session.find(:xpath, XPath.descendant[XPath.attr(:class).is('multiple')], match: :prefer_exact, exact: true)
expect(result.text).to eq('multiple one')
end
it 'finds a single exact match when there also are inexact matches' do
result = @session.find(:xpath, XPath.descendant[XPath.attr(:class).is('almost_singular')], match: :prefer_exact, exact: true)
expect(result.text).to eq('almost singular')
end
it 'raises an error if there are multiple inexact matches' do
expect do
@session.find(:xpath, XPath.descendant[XPath.attr(:class).is('almost_singul')], match: :prefer_exact, exact: true)
end.to raise_error(Capybara::ElementNotFound)
end
it 'raises an error if there is a single inexact match' do
expect do
@session.find(:xpath, XPath.descendant[XPath.attr(:class).is('almost_singular but')], match: :prefer_exact, exact: true)
end.to raise_error(Capybara::ElementNotFound)
end
it 'raises an error if there is no match' do
expect do
@session.find(:xpath, XPath.descendant[XPath.attr(:class).is('does-not-exist')], match: :prefer_exact, exact: true)
end.to raise_error(Capybara::ElementNotFound)
end
end
end
it 'defaults to `Capybara.match`' do
Capybara.match = :one
expect do
@session.find(:css, '.multiple')
end.to raise_error(Capybara::Ambiguous)
Capybara.match = :first
expect(@session.find(:css, '.multiple').text).to eq('multiple one')
end
it 'raises an error when unknown option given' do
expect do
@session.find(:css, '.singular', match: :schmoo)
end.to raise_error(ArgumentError)
end
end
it 'supports a custom filter block' do
expect(@session.find(:css, 'input', &:disabled?)[:name]).to eq('disabled_text')
end
context 'with spatial filters', requires: [:spatial] do
before do
@session.visit('/spatial')
end
let :center do
@session.find(:css, 'div.center')
end
it 'should find an element above another element' do
expect(@session.find(:css, 'div:not(.corner)', above: center).text).to eq('2')
end
it 'should find an element below another element' do
expect(@session.find(:css, 'div:not(.corner):not(.footer)', below: center).text).to eq('8')
end
it 'should find an element left of another element' do
expect(@session.find(:css, 'div:not(.corner)', left_of: center).text).to eq('4')
end
it 'should find an element right of another element' do
expect(@session.find(:css, 'div:not(.corner)', right_of: center).text).to eq('6')
end
it 'should combine spatial filters' do
expect(@session.find(:css, 'div', left_of: center, above: center).text).to eq('1')
expect(@session.find(:css, 'div', right_of: center, below: center).text).to eq('9')
end
it 'should find an element "near" another element' do
expect(@session.find(:css, 'div.distance', near: center).text).to eq('2')
end
end
context 'within a scope' do
before do
@session.visit('/with_scope')
end
it 'should find the an element using the given locator' do
@session.within(:xpath, "//div[@id='for_bar']") do
expect(@session.find('.//li[1]').text).to match(/With Simple HTML/)
end
end
it 'should support pseudo selectors' do
@session.within(:xpath, "//div[@id='for_bar']") do
expect(@session.find(:css, 'input:disabled').value).to eq('James')
end
end
end
it 'should raise if selector type is unknown' do
expect do
@session.find(:unknown, '//h1')
end.to raise_error(ArgumentError)
end
context 'with Capybara.test_id' do
it 'should not match on it when nil' do
Capybara.test_id = nil
expect(@session).not_to have_field('test_id')
end
it 'should work with the attribute set to `data-test-id` attribute' do
Capybara.test_id = 'data-test-id'
expect(@session.find(:field, 'test_id')[:id]).to eq 'test_field'
end
it 'should use a different attribute if set' do
Capybara.test_id = 'data-other-test-id'
expect(@session.find(:field, 'test_id')[:id]).to eq 'normal'
end
it 'should find a link with the test_id' do
Capybara.test_id = 'data-test-id'
expect(@session.find(:link, 'test-foo')[:id]).to eq 'foo'
end
end
it 'should warn if passed count options' do
allow(Capybara::Helpers).to receive(:warn)
@session.find('//h1', count: 44)
expect(Capybara::Helpers).to have_received(:warn).with(/'find' does not support count options/)
end
end
| ruby | MIT | b3325b198464b806f07ec2011ceb532d6d5cf4ab | 2026-01-04T15:38:10.098638Z | false |
teamcapybara/capybara | https://github.com/teamcapybara/capybara/blob/b3325b198464b806f07ec2011ceb532d6d5cf4ab/lib/capybara/spec/session/assert_title_spec.rb | lib/capybara/spec/session/assert_title_spec.rb | # frozen_string_literal: true
Capybara::SpecHelper.spec '#assert_title' do
before do
@session.visit('/with_js')
end
it "should not raise if the page's title contains the given string" do
expect do
@session.assert_title('js')
end.not_to raise_error
end
it 'should not raise when given an empty string' do
expect do
@session.assert_title('')
end.not_to raise_error
end
it 'should allow regexp matches' do
expect do
@session.assert_title(/w[a-z]{3}_js/)
end.not_to raise_error
expect do
@session.assert_title(/w[a-z]{10}_js/)
end.to raise_error(Capybara::ExpectationNotMet, 'expected "with_js" to match /w[a-z]{10}_js/')
end
it 'should wait for title', requires: [:js] do
@session.click_link('Change title')
expect do
@session.assert_title('changed title', wait: 3)
end.not_to raise_error
end
it "should raise error if the title doesn't contain the given string" do
expect do
@session.assert_title('monkey')
end.to raise_error(Capybara::ExpectationNotMet, 'expected "with_js" to include "monkey"')
end
it 'should not normalize given title' do
@session.visit('/with_js')
expect { @session.assert_title(' with_js ') }.to raise_error(Capybara::ExpectationNotMet)
end
it 'should match correctly normalized title' do
uri = Addressable::URI.parse('/with_title')
uri.query_values = { title: ' with space title ' }
@session.visit(uri.to_s)
@session.assert_title(' with space title')
expect { @session.assert_title('with space title') }.to raise_error(Capybara::ExpectationNotMet)
end
it 'should not normalize given title in error message' do
expect do
@session.assert_title(2)
end.to raise_error(Capybara::ExpectationNotMet, 'expected "with_js" to include "2"')
end
end
Capybara::SpecHelper.spec '#assert_no_title' do
before do
@session.visit('/with_js')
end
it 'should raise error if the title contains the given string' do
expect do
@session.assert_no_title('with_j')
end.to raise_error(Capybara::ExpectationNotMet, 'expected "with_js" not to include "with_j"')
end
it 'should allow regexp matches' do
expect do
@session.assert_no_title(/w[a-z]{3}_js/)
end.to raise_error(Capybara::ExpectationNotMet, 'expected "with_js" not to match /w[a-z]{3}_js/')
@session.assert_no_title(/monkey/)
end
it 'should wait for title to disappear', requires: [:js] do
@session.click_link('Change title')
expect do
@session.assert_no_title('with_js', wait: 3)
end.not_to raise_error
end
it "should not raise if the title doesn't contain the given string" do
expect do
@session.assert_no_title('monkey')
end.not_to raise_error
end
end
| ruby | MIT | b3325b198464b806f07ec2011ceb532d6d5cf4ab | 2026-01-04T15:38:10.098638Z | false |
teamcapybara/capybara | https://github.com/teamcapybara/capybara/blob/b3325b198464b806f07ec2011ceb532d6d5cf4ab/lib/capybara/spec/session/has_ancestor_spec.rb | lib/capybara/spec/session/has_ancestor_spec.rb | # frozen_string_literal: true
Capybara::SpecHelper.spec '#have_ancestor' do
before do
@session.visit('/with_html')
end
it 'should assert an ancestor using the given locator' do
el = @session.find(:css, '#ancestor1')
expect(el).to have_ancestor(:css, '#ancestor2')
end
it 'should assert an ancestor even if not parent' do
el = @session.find(:css, '#child')
expect(el).to have_ancestor(:css, '#ancestor3')
end
it 'should not raise an error if there are multiple matches' do
el = @session.find(:css, '#child')
expect(el).to have_ancestor(:css, 'div')
end
it 'should allow counts to be specified' do
el = @session.find(:css, '#child')
expect do
expect(el).to have_ancestor(:css, 'div').once
end.to raise_error(RSpec::Expectations::ExpectationNotMetError)
expect(el).to have_ancestor(:css, 'div').exactly(3).times
end
end
Capybara::SpecHelper.spec '#have_no_ancestor' do
before do
@session.visit('/with_html')
end
it 'should assert no matching ancestor' do
el = @session.find(:css, '#ancestor1')
expect(el).to have_no_ancestor(:css, '#child')
expect(el).to have_no_ancestor(:css, '#ancestor1_sibling')
expect(el).not_to have_ancestor(:css, '#child')
expect(el).not_to have_ancestor(:css, '#ancestor1_sibling')
end
end
| ruby | MIT | b3325b198464b806f07ec2011ceb532d6d5cf4ab | 2026-01-04T15:38:10.098638Z | false |
teamcapybara/capybara | https://github.com/teamcapybara/capybara/blob/b3325b198464b806f07ec2011ceb532d6d5cf4ab/lib/capybara/spec/session/save_and_open_page_spec.rb | lib/capybara/spec/session/save_and_open_page_spec.rb | # frozen_string_literal: true
require 'launchy'
Capybara::SpecHelper.spec '#save_and_open_page' do
before do
@session.visit '/foo'
end
after do
Dir.glob('capybara-*.html').each do |file|
FileUtils.rm(file)
end
end
it 'sends open method to launchy' do
allow(Launchy).to receive(:open)
@session.save_and_open_page
expect(Launchy).to have_received(:open).with(/capybara-\d+\.html/)
end
end
| ruby | MIT | b3325b198464b806f07ec2011ceb532d6d5cf4ab | 2026-01-04T15:38:10.098638Z | false |
teamcapybara/capybara | https://github.com/teamcapybara/capybara/blob/b3325b198464b806f07ec2011ceb532d6d5cf4ab/lib/capybara/spec/session/click_link_or_button_spec.rb | lib/capybara/spec/session/click_link_or_button_spec.rb | # frozen_string_literal: true
Capybara::SpecHelper.spec '#click_link_or_button' do
it 'should click on a link' do
@session.visit('/with_html')
@session.click_link_or_button('labore')
expect(@session).to have_content('Bar')
end
it 'should click on a button' do
@session.visit('/form')
@session.click_link_or_button('awe123')
expect(extract_results(@session)['first_name']).to eq('John')
end
it 'should click on a button with no type attribute' do
@session.visit('/form')
@session.click_link_or_button('no_type')
expect(extract_results(@session)['first_name']).to eq('John')
end
it 'should be aliased as click_on' do
@session.visit('/form')
@session.click_on('awe123')
expect(extract_results(@session)['first_name']).to eq('John')
end
it 'should wait for asynchronous load', requires: [:js] do
Capybara.default_max_wait_time = 2
@session.visit('/with_js')
@session.click_link('Click me')
@session.click_link_or_button('Has been clicked')
end
it 'casts to string' do
@session.visit('/form')
@session.click_link_or_button(:awe123)
expect(extract_results(@session)['first_name']).to eq('John')
end
context 'with test_id' do
it 'should click on a button' do
Capybara.test_id = 'data-test-id'
@session.visit('/form')
@session.click_link_or_button('test_id_button')
expect(extract_results(@session)['first_name']).to eq('John')
end
end
context 'with :exact option' do
context 'when `false`' do
it 'clicks on approximately matching link' do
@session.visit('/with_html')
@session.click_link_or_button('abore', exact: false)
expect(@session).to have_content('Bar')
end
it 'clicks on approximately matching button' do
@session.visit('/form')
@session.click_link_or_button('awe', exact: false)
expect(extract_results(@session)['first_name']).to eq('John')
end
end
context 'when `true`' do
it 'does not click on link which matches approximately' do
@session.visit('/with_html')
msg = 'Unable to find link or button "abore"'
expect do
@session.click_link_or_button('abore', exact: true)
end.to raise_error(Capybara::ElementNotFound, msg)
end
it 'does not click on approximately matching button' do
@session.visit('/form')
msg = 'Unable to find link or button "awe"'
expect do
@session.click_link_or_button('awe', exact: true)
end.to raise_error(Capybara::ElementNotFound, msg)
end
end
end
context "with a locator that doesn't exist" do
it 'should raise an error' do
@session.visit('/with_html')
msg = 'Unable to find link or button "does not exist"'
expect do
@session.click_link_or_button('does not exist')
end.to raise_error(Capybara::ElementNotFound, msg)
end
end
context 'with :disabled option' do
it 'ignores disabled buttons when false' do
@session.visit('/form')
expect do
@session.click_link_or_button('Disabled button', disabled: false)
end.to raise_error(Capybara::ElementNotFound)
end
it 'ignores disabled buttons by default' do
@session.visit('/form')
expect do
@session.click_link_or_button('Disabled button')
end.to raise_error(Capybara::ElementNotFound)
end
it 'happily clicks on links which incorrectly have the disabled attribute' do
@session.visit('/with_html')
@session.click_link_or_button('Disabled link')
expect(@session).to have_content('Bar')
end
end
it 'should return the element clicked' do
@session.visit('/with_html')
link = @session.find(:link, 'Blank Anchor')
expect(@session.click_link_or_button('Blank Anchor')).to eq link
end
context 'with enable_aria_label' do
it 'should click on link' do
@session.visit('/with_html')
expect do
@session.click_link_or_button('Go to simple', enable_aria_label: true)
end.not_to raise_error
end
it 'should click on button' do
@session.visit('/form')
expect do
@session.click_link_or_button('Aria button', enable_aria_label: true)
end.not_to raise_error
end
end
end
| ruby | MIT | b3325b198464b806f07ec2011ceb532d6d5cf4ab | 2026-01-04T15:38:10.098638Z | false |
teamcapybara/capybara | https://github.com/teamcapybara/capybara/blob/b3325b198464b806f07ec2011ceb532d6d5cf4ab/lib/capybara/spec/session/assert_style_spec.rb | lib/capybara/spec/session/assert_style_spec.rb | # frozen_string_literal: true
Capybara::SpecHelper.spec '#assert_matches_style', requires: [:css] do
it 'should not raise if the elements style contains the given properties' do
@session.visit('/with_html')
expect do
@session.find(:css, '#first').assert_matches_style(display: 'block')
end.not_to raise_error
end
it "should raise error if the elements style doesn't contain the given properties" do
@session.visit('/with_html')
expect do
@session.find(:css, '#first').assert_matches_style(display: 'inline')
end.to raise_error(Capybara::ExpectationNotMet, 'Expected node to have styles {"display"=>"inline"}. Actual styles were {"display"=>"block"}')
end
it 'should wait for style', requires: %i[css js] do
@session.visit('/with_js')
el = @session.find(:css, '#change')
@session.click_link('Change size')
expect do
el.assert_matches_style({ 'font-size': '50px' }, wait: 3)
end.not_to raise_error
end
end
| ruby | MIT | b3325b198464b806f07ec2011ceb532d6d5cf4ab | 2026-01-04T15:38:10.098638Z | false |
teamcapybara/capybara | https://github.com/teamcapybara/capybara/blob/b3325b198464b806f07ec2011ceb532d6d5cf4ab/lib/capybara/spec/session/go_forward_spec.rb | lib/capybara/spec/session/go_forward_spec.rb | # frozen_string_literal: true
Capybara::SpecHelper.spec '#go_forward', requires: [:js] do
it 'should fetch a response from the driver from the previous page' do
@session.visit('/')
expect(@session).to have_content('Hello world!')
@session.visit('/foo')
expect(@session).to have_content('Another World')
@session.go_back
expect(@session).to have_content('Hello world!')
@session.go_forward
expect(@session).to have_content('Another World')
end
end
| ruby | MIT | b3325b198464b806f07ec2011ceb532d6d5cf4ab | 2026-01-04T15:38:10.098638Z | false |
teamcapybara/capybara | https://github.com/teamcapybara/capybara/blob/b3325b198464b806f07ec2011ceb532d6d5cf4ab/lib/capybara/spec/session/has_select_spec.rb | lib/capybara/spec/session/has_select_spec.rb | # frozen_string_literal: true
Capybara::SpecHelper.spec '#has_select?' do
before { @session.visit('/form') }
it 'should be true if the field is on the page' do
expect(@session).to have_select('Locale')
expect(@session).to have_select('form_region')
expect(@session).to have_select('Languages')
expect(@session).to have_select(:Languages)
end
it 'should be false if the field is not on the page' do
expect(@session).not_to have_select('Monkey')
end
context 'with selected value' do
it 'should be true if a field with the given value is on the page' do
expect(@session).to have_select('form_locale', selected: 'English')
expect(@session).to have_select('Region', selected: 'Norway')
expect(@session).to have_select('Underwear', selected: [
'Boxerbriefs', 'Briefs', 'Commando', "Frenchman's Pantalons", 'Long Johns'
])
end
it 'should be false if the given field is not on the page' do
expect(@session).not_to have_select('Locale', selected: 'Swedish')
expect(@session).not_to have_select('Does not exist', selected: 'John')
expect(@session).not_to have_select('City', selected: 'Not there')
expect(@session).not_to have_select('Underwear', selected: [
'Boxerbriefs', 'Briefs', 'Commando', "Frenchman's Pantalons", 'Long Johns', 'Nonexistent'
])
expect(@session).not_to have_select('Underwear', selected: [
'Boxerbriefs', 'Briefs', 'Boxers', 'Commando', "Frenchman's Pantalons", 'Long Johns'
])
expect(@session).not_to have_select('Underwear', selected: [
'Boxerbriefs', 'Briefs', 'Commando', "Frenchman's Pantalons"
])
end
it 'should be true after the given value is selected' do
@session.select('Swedish', from: 'Locale')
expect(@session).to have_select('Locale', selected: 'Swedish')
end
it 'should be false after a different value is selected' do
@session.select('Swedish', from: 'Locale')
expect(@session).not_to have_select('Locale', selected: 'English')
end
it 'should be true after the given values are selected' do
@session.select('Boxers', from: 'Underwear')
expect(@session).to have_select('Underwear', selected: [
'Boxerbriefs', 'Briefs', 'Boxers', 'Commando', "Frenchman's Pantalons", 'Long Johns'
])
end
it 'should be false after one of the values is unselected' do
@session.unselect('Briefs', from: 'Underwear')
expect(@session).not_to have_select('Underwear', selected: [
'Boxerbriefs', 'Briefs', 'Commando', "Frenchman's Pantalons", 'Long Johns'
])
end
it "should be true even when the selected option invisible, regardless of the select's visibility" do
expect(@session).to have_select('Icecream', visible: :hidden, selected: 'Chocolate')
expect(@session).to have_select('Sorbet', selected: 'Vanilla')
end
end
context 'with partial select' do
it 'should be true if a field with the given partial values is on the page' do
expect(@session).to have_select('Underwear', with_selected: %w[Boxerbriefs Briefs])
end
it 'should be false if a field with the given partial values is not on the page' do
expect(@session).not_to have_select('Underwear', with_selected: %w[Boxerbriefs Boxers])
end
it 'should be true after the given partial value is selected' do
@session.select('Boxers', from: 'Underwear')
expect(@session).to have_select('Underwear', with_selected: %w[Boxerbriefs Boxers])
end
it 'should be false after one of the given partial values is unselected' do
@session.unselect('Briefs', from: 'Underwear')
expect(@session).not_to have_select('Underwear', with_selected: %w[Boxerbriefs Briefs])
end
it "should be true even when the selected values are invisible, regardless of the select's visibility" do
expect(@session).to have_select('Dessert', visible: :hidden, with_options: %w[Pudding Tiramisu])
expect(@session).to have_select('Cake', with_selected: ['Chocolate Cake', 'Sponge Cake'])
end
it 'should support non array partial values' do
expect(@session).to have_select('Underwear', with_selected: 'Briefs')
expect(@session).not_to have_select('Underwear', with_selected: 'Boxers')
end
end
context 'with exact options' do
it 'should be true if a field with the given options is on the page' do
expect(@session).to have_select('Region', options: %w[Norway Sweden Finland])
expect(@session).to have_select('Tendency', options: [])
end
it 'should be false if the given field is not on the page' do
expect(@session).not_to have_select('Locale', options: ['Swedish'])
expect(@session).not_to have_select('Does not exist', options: ['John'])
expect(@session).not_to have_select('City', options: ['London', 'Made up city'])
expect(@session).not_to have_select('Region', options: %w[Norway Sweden])
expect(@session).not_to have_select('Region', options: %w[Norway Norway Norway])
end
it 'should be true even when the options are invisible, if the select itself is invisible' do
expect(@session).to have_select('Icecream', visible: :hidden, options: %w[Chocolate Vanilla Strawberry])
end
end
context 'with enabled options' do
it 'should be true if the listed options exist and are enabled' do
expect(@session).to have_select('form_title', enabled_options: %w[Mr Mrs Miss])
end
it 'should be false if the listed options do not exist' do
expect(@session).not_to have_select('form_title', enabled_options: ['Not there'])
end
it 'should be false if the listed option exists but is not enabled' do
expect(@session).not_to have_select('form_title', enabled_options: %w[Mr Mrs Miss Other])
end
end
context 'with disabled options' do
it 'should be true if the listed options exist and are disabled' do
expect(@session).to have_select('form_title', disabled_options: ['Other'])
end
it 'should be false if the listed options do not exist' do
expect(@session).not_to have_select('form_title', disabled_options: ['Not there'])
end
it 'should be false if the listed option exists but is not disabled' do
expect(@session).not_to have_select('form_title', disabled_options: %w[Other Mrs])
end
end
context 'with partial options' do
it 'should be true if a field with the given partial options is on the page' do
expect(@session).to have_select('Region', with_options: %w[Norway Sweden])
expect(@session).to have_select('City', with_options: ['London'])
end
it 'should be false if a field with the given partial options is not on the page' do
expect(@session).not_to have_select('Locale', with_options: ['Uruguayan'])
expect(@session).not_to have_select('Does not exist', with_options: ['John'])
expect(@session).not_to have_select('Region', with_options: %w[Norway Sweden Finland Latvia])
end
it 'should be true even when the options are invisible, if the select itself is invisible' do
expect(@session).to have_select('Icecream', visible: :hidden, with_options: %w[Vanilla Strawberry])
end
end
context 'with multiple option' do
it 'should find multiple selects if true' do
expect(@session).to have_select('form_languages', multiple: true)
expect(@session).not_to have_select('form_other_title', multiple: true)
end
it 'should not find multiple selects if false' do
expect(@session).not_to have_select('form_languages', multiple: false)
expect(@session).to have_select('form_other_title', multiple: false)
end
it 'should find both if not specified' do
expect(@session).to have_select('form_languages')
expect(@session).to have_select('form_other_title')
end
end
it 'should raise an error if an invalid option is passed' do
expect do
expect(@session).to have_select('form_languages', invalid: true)
end.to raise_error(ArgumentError, 'Invalid option(s) :invalid, should be one of :above, :below, :left_of, :right_of, :near, :count, :minimum, :maximum, :between, :text, :id, :class, :style, :visible, :obscured, :exact, :exact_text, :normalize_ws, :match, :wait, :filter_set, :focused, :disabled, :name, :placeholder, :options, :enabled_options, :disabled_options, :selected, :with_selected, :multiple, :with_options')
end
it 'should support locator-less usage' do
expect(@session.has_select?(with_options: %w[Norway Sweden])).to be true
expect(@session).to have_select(with_options: ['London'])
expect(@session.has_select?(with_selected: %w[Commando Boxerbriefs])).to be true
expect(@session).to have_select(with_selected: ['Briefs'])
end
end
Capybara::SpecHelper.spec '#has_no_select?' do
before { @session.visit('/form') }
it 'should be false if the field is on the page' do
expect(@session).not_to have_no_select('Locale')
expect(@session).not_to have_no_select('form_region')
expect(@session).not_to have_no_select('Languages')
end
it 'should be true if the field is not on the page' do
expect(@session).to have_no_select('Monkey')
end
context 'with selected value' do
it 'should be false if a field with the given value is on the page' do
expect(@session).not_to have_no_select('form_locale', selected: 'English')
expect(@session).not_to have_no_select('Region', selected: 'Norway')
expect(@session).not_to have_no_select('Underwear', selected: [
'Boxerbriefs', 'Briefs', 'Commando', "Frenchman's Pantalons", 'Long Johns'
])
end
it 'should be true if the given field is not on the page' do
expect(@session).to have_no_select('Locale', selected: 'Swedish')
expect(@session).to have_no_select('Does not exist', selected: 'John')
expect(@session).to have_no_select('City', selected: 'Not there')
expect(@session).to have_no_select('Underwear', selected: [
'Boxerbriefs', 'Briefs', 'Commando', "Frenchman's Pantalons", 'Long Johns', 'Nonexistent'
])
expect(@session).to have_no_select('Underwear', selected: [
'Boxerbriefs', 'Briefs', 'Boxers', 'Commando', "Frenchman's Pantalons", 'Long Johns'
])
expect(@session).to have_no_select('Underwear', selected: [
'Boxerbriefs', 'Briefs', 'Commando', "Frenchman's Pantalons"
])
end
it 'should be false after the given value is selected' do
@session.select('Swedish', from: 'Locale')
expect(@session).not_to have_no_select('Locale', selected: 'Swedish')
end
it 'should be true after a different value is selected' do
@session.select('Swedish', from: 'Locale')
expect(@session).to have_no_select('Locale', selected: 'English')
end
it 'should be false after the given values are selected' do
@session.select('Boxers', from: 'Underwear')
expect(@session).not_to have_no_select('Underwear', selected: [
'Boxerbriefs', 'Briefs', 'Boxers', 'Commando', "Frenchman's Pantalons", 'Long Johns'
])
end
it 'should be true after one of the values is unselected' do
@session.unselect('Briefs', from: 'Underwear')
expect(@session).to have_no_select('Underwear', selected: [
'Boxerbriefs', 'Briefs', 'Commando', "Frenchman's Pantalons", 'Long Johns'
])
end
end
context 'with partial select' do
it 'should be false if a field with the given partial values is on the page' do
expect(@session).not_to have_no_select('Underwear', with_selected: %w[Boxerbriefs Briefs])
end
it 'should be true if a field with the given partial values is not on the page' do
expect(@session).to have_no_select('Underwear', with_selected: %w[Boxerbriefs Boxers])
end
it 'should be false after the given partial value is selected' do
@session.select('Boxers', from: 'Underwear')
expect(@session).not_to have_no_select('Underwear', with_selected: %w[Boxerbriefs Boxers])
end
it 'should be true after one of the given partial values is unselected' do
@session.unselect('Briefs', from: 'Underwear')
expect(@session).to have_no_select('Underwear', with_selected: %w[Boxerbriefs Briefs])
end
it 'should support non array partial values' do
expect(@session).not_to have_no_select('Underwear', with_selected: 'Briefs')
expect(@session).to have_no_select('Underwear', with_selected: 'Boxers')
end
end
context 'with exact options' do
it 'should be false if a field with the given options is on the page' do
expect(@session).not_to have_no_select('Region', options: %w[Norway Sweden Finland])
end
it 'should be true if the given field is not on the page' do
expect(@session).to have_no_select('Locale', options: ['Swedish'])
expect(@session).to have_no_select('Does not exist', options: ['John'])
expect(@session).to have_no_select('City', options: ['London', 'Made up city'])
expect(@session).to have_no_select('Region', options: %w[Norway Sweden])
expect(@session).to have_no_select('Region', options: %w[Norway Norway Norway])
end
end
context 'with partial options' do
it 'should be false if a field with the given partial options is on the page' do
expect(@session).not_to have_no_select('Region', with_options: %w[Norway Sweden])
expect(@session).not_to have_no_select('City', with_options: ['London'])
end
it 'should be true if a field with the given partial options is not on the page' do
expect(@session).to have_no_select('Locale', with_options: ['Uruguayan'])
expect(@session).to have_no_select('Does not exist', with_options: ['John'])
expect(@session).to have_no_select('Region', with_options: %w[Norway Sweden Finland Latvia])
end
end
it 'should support locator-less usage' do
expect(@session.has_no_select?(with_options: %w[Norway Sweden Finland Latvia])).to be true
expect(@session).to have_no_select(with_options: ['New London'])
expect(@session.has_no_select?(id: 'form_underwear', with_selected: ['Boxers'])).to be true
expect(@session).to have_no_select(id: 'form_underwear', with_selected: %w[Commando Boxers])
end
end
| ruby | MIT | b3325b198464b806f07ec2011ceb532d6d5cf4ab | 2026-01-04T15:38:10.098638Z | false |
teamcapybara/capybara | https://github.com/teamcapybara/capybara/blob/b3325b198464b806f07ec2011ceb532d6d5cf4ab/lib/capybara/spec/session/dismiss_prompt_spec.rb | lib/capybara/spec/session/dismiss_prompt_spec.rb | # frozen_string_literal: true
Capybara::SpecHelper.spec '#dismiss_prompt', requires: [:modals] do
before do
@session.visit('/with_js')
end
it 'should dismiss the prompt' do
@session.dismiss_prompt do
@session.click_link('Open prompt')
end
expect(@session).to have_xpath("//a[@id='open-prompt' and @response='dismissed']")
end
it 'should return the message presented' do
message = @session.dismiss_prompt do
@session.click_link('Open prompt')
end
expect(message).to eq('Prompt opened')
end
end
| ruby | MIT | b3325b198464b806f07ec2011ceb532d6d5cf4ab | 2026-01-04T15:38:10.098638Z | false |
teamcapybara/capybara | https://github.com/teamcapybara/capybara/blob/b3325b198464b806f07ec2011ceb532d6d5cf4ab/lib/capybara/spec/session/selectors_spec.rb | lib/capybara/spec/session/selectors_spec.rb | # frozen_string_literal: true
Capybara::SpecHelper.spec Capybara::Selector do
before do
@session.visit('/form')
end
describe ':label selector' do
it 'finds a label by text' do
expect(@session.find(:label, 'Customer Name').text).to eq 'Customer Name'
end
it 'finds a label by for attribute string' do
expect(@session.find(:label, for: 'form_other_title')['for']).to eq 'form_other_title'
end
it 'finds a label for for attribute regex' do
expect(@session.find(:label, for: /_other_title/)['for']).to eq 'form_other_title'
end
it 'finds a label from nested input using :for filter with id string' do
expect(@session.find(:label, for: 'nested_label').text).to eq 'Nested Label'
end
it 'finds a label from nested input using :for filter with id regexp' do
expect(@session.find(:label, for: /nested_lab/).text).to eq 'Nested Label'
end
it 'finds a label from nested input using :for filter with element' do
input = @session.find(:id, 'nested_label')
expect(@session.find(:label, for: input).text).to eq 'Nested Label'
end
it 'finds a label from nested input using :for filter with element when no id on label' do
input = @session.find(:css, '#wrapper_label').find(:css, 'input')
expect(@session.find(:label, for: input).text).to eq 'Wrapper Label'
end
it 'finds the label for an non-nested element when using :for filter' do
select = @session.find(:id, 'form_other_title')
expect(@session.find(:label, for: select)['for']).to eq 'form_other_title'
end
context 'with exact option' do
it 'matches substrings' do
expect(@session.find(:label, 'Customer Na', exact: false).text).to eq 'Customer Name'
end
it "doesn't match substrings" do
expect { @session.find(:label, 'Customer Na', exact: true) }.to raise_error(Capybara::ElementNotFound)
end
end
end
describe 'field selectors' do
context 'with :id option' do
it 'can find specifically by id' do
expect(@session.find(:field, id: 'customer_email').value).to eq 'ben@ben.com'
end
it 'can find by regex' do
expect(@session.find(:field, id: /ustomer.emai/).value).to eq 'ben@ben.com'
end
it 'can find by case-insensitive id' do
expect(@session.find(:field, id: /StOmer.emAI/i).value).to eq 'ben@ben.com'
end
end
it 'can find specifically by name string' do
expect(@session.find(:field, name: 'form[other_title]')['id']).to eq 'form_other_title'
end
it 'can find specifically by name regex' do
expect(@session.find(:field, name: /form\[other_.*\]/)['id']).to eq 'form_other_title'
end
it 'can find specifically by placeholder string' do
expect(@session.find(:field, placeholder: 'FirstName')['id']).to eq 'form_first_name'
end
it 'can find specifically by placeholder regex' do
expect(@session.find(:field, placeholder: /FirstN.*/)['id']).to eq 'form_first_name'
end
it 'can find by type' do
expect(@session.find(:field, 'Confusion', type: 'checkbox')['id']).to eq 'confusion_checkbox'
expect(@session.find(:field, 'Confusion', type: 'text')['id']).to eq 'confusion_text'
expect(@session.find(:field, 'Confusion', type: 'textarea')['id']).to eq 'confusion_textarea'
end
it 'can find by class' do
expect(@session.find(:field, class: 'confusion-checkbox')['id']).to eq 'confusion_checkbox'
expect(@session).to have_selector(:field, class: 'confusion', count: 3)
expect(@session.find(:field, class: %w[confusion confusion-textarea])['id']).to eq 'confusion_textarea'
end
end
end
| ruby | MIT | b3325b198464b806f07ec2011ceb532d6d5cf4ab | 2026-01-04T15:38:10.098638Z | false |
teamcapybara/capybara | https://github.com/teamcapybara/capybara/blob/b3325b198464b806f07ec2011ceb532d6d5cf4ab/lib/capybara/spec/session/has_none_selectors_spec.rb | lib/capybara/spec/session/has_none_selectors_spec.rb | # frozen_string_literal: true
Capybara::SpecHelper.spec '#have_none_of_selectors' do
before do
@session.visit('/with_html')
end
it 'should be false if any of the given locators are on the page' do
expect do
expect(@session).to have_none_of_selectors(:xpath, '//p', '//a')
end.to raise_error RSpec::Expectations::ExpectationNotMetError
expect do
expect(@session).to have_none_of_selectors(:css, 'p a#foo')
end.to raise_error RSpec::Expectations::ExpectationNotMetError
end
it 'should be true if none of the given locators are on the page' do
expect(@session).to have_none_of_selectors(:xpath, '//abbr', '//td')
expect(@session).to have_none_of_selectors(:css, 'p a#doesnotexist', 'abbr')
end
it 'should use default selector' do
Capybara.default_selector = :css
expect(@session).to have_none_of_selectors('p a#doesnotexist', 'abbr')
expect do
expect(@session).to have_none_of_selectors('abbr', 'p a#foo')
end.to raise_error RSpec::Expectations::ExpectationNotMetError
end
context 'should respect scopes' do
it 'when used with `within`' do
@session.within "//p[@id='first']" do
expect do
expect(@session).to have_none_of_selectors(".//a[@id='foo']")
end.to raise_error RSpec::Expectations::ExpectationNotMetError
expect(@session).to have_none_of_selectors(".//a[@id='red']")
end
end
it 'when called on an element' do
el = @session.find "//p[@id='first']"
expect do
expect(el).to have_none_of_selectors(".//a[@id='foo']")
end.to raise_error RSpec::Expectations::ExpectationNotMetError
expect(el).to have_none_of_selectors(".//a[@id='red']")
end
end
context 'with options' do
it 'should apply the options to all locators' do
expect do
expect(@session).to have_none_of_selectors('//p//a', text: 'Redirect')
end.to raise_error RSpec::Expectations::ExpectationNotMetError
expect(@session).to have_none_of_selectors('//p', text: 'Doesnotexist')
end
it 'should discard all matches where the given regexp is matched' do
expect do
expect(@session).to have_none_of_selectors('//p//a', text: /re[dab]i/i, count: 1)
end.to raise_error RSpec::Expectations::ExpectationNotMetError
expect(@session).to have_none_of_selectors('//p//a', text: /Red$/)
end
end
context 'with wait', requires: [:js] do
it 'should not find elements if they appear after given wait duration' do
@session.visit('/with_js')
@session.click_link('Click me')
expect(@session).to have_none_of_selectors(:css, '#new_field', 'a#has-been-clicked', wait: 0.1)
end
end
it 'cannot be negated' do
expect do
expect(@session).not_to have_none_of_selectors(:css, 'p a#foo', 'h2#h2one', 'h2#h2two')
end.to raise_error ArgumentError
end
end
| ruby | MIT | b3325b198464b806f07ec2011ceb532d6d5cf4ab | 2026-01-04T15:38:10.098638Z | false |
teamcapybara/capybara | https://github.com/teamcapybara/capybara/blob/b3325b198464b806f07ec2011ceb532d6d5cf4ab/lib/capybara/spec/session/has_any_selectors_spec.rb | lib/capybara/spec/session/has_any_selectors_spec.rb | # frozen_string_literal: true
Capybara::SpecHelper.spec '#have_any_of_selectors' do
before do
@session.visit('/with_html')
end
it 'should be true if any of the given selectors are on the page' do
expect(@session).to have_any_of_selectors(:css, 'p a#foo', 'h2#blah', 'h2#h2two')
end
it 'should be false if none of the given selectors are not on the page' do
expect do
expect(@session).to have_any_of_selectors(:css, 'span a#foo', 'h2#h2nope', 'h2#h2one_no')
end.to raise_error RSpec::Expectations::ExpectationNotMetError
end
it 'should use default selector' do
Capybara.default_selector = :css
expect(@session).to have_any_of_selectors('p a#foo', 'h2#h2two', 'a#not_on_page')
expect do
expect(@session).to have_any_of_selectors('p a#blah', 'h2#h2three')
end.to raise_error RSpec::Expectations::ExpectationNotMetError
end
it 'should be negateable' do
expect(@session).not_to have_any_of_selectors(:css, 'span a#foo', 'h2#h2nope', 'h2#h2one_no')
end
end
| ruby | MIT | b3325b198464b806f07ec2011ceb532d6d5cf4ab | 2026-01-04T15:38:10.098638Z | false |
teamcapybara/capybara | https://github.com/teamcapybara/capybara/blob/b3325b198464b806f07ec2011ceb532d6d5cf4ab/lib/capybara/spec/session/sibling_spec.rb | lib/capybara/spec/session/sibling_spec.rb | # frozen_string_literal: true
Capybara::SpecHelper.spec '#sibling' do
before do
@session.visit('/with_html')
end
after do
Capybara::Selector.remove(:monkey)
end
it 'should find a prior sibling element using the given locator' do
el = @session.find(:css, '#mid_sibling')
expect(el.sibling('//div[@data-pre]')[:id]).to eq('pre_sibling')
end
it 'should find a following sibling element using the given locator' do
el = @session.find(:css, '#mid_sibling')
expect(el.sibling('//div[@data-post]')[:id]).to eq('post_sibling')
end
it 'should raise an error if there are multiple matches' do
el = @session.find(:css, '#mid_sibling')
expect { el.sibling('//div') }.to raise_error(Capybara::Ambiguous)
end
context 'with css selectors' do
it 'should find the first element using the given locator' do
el = @session.find(:css, '#mid_sibling')
expect(el.sibling(:css, '#pre_sibling')).to have_text('Pre Sibling')
expect(el.sibling(:css, '#post_sibling')).to have_text('Post Sibling')
end
end
context 'with custom selector' do
it 'should use the custom selector' do
Capybara.add_selector(:data_attribute) do
xpath { |attr| ".//*[@data-#{attr}]" }
end
el = @session.find(:css, '#mid_sibling')
expect(el.sibling(:data_attribute, 'pre').text).to eq('Pre Sibling')
expect(el.sibling(:data_attribute, 'post').text).to eq('Post Sibling')
end
end
it 'should raise ElementNotFound with a useful default message if nothing was found' do
el = @session.find(:css, '#child')
expect do
el.sibling(:xpath, '//div[@id="nosuchthing"]')
end.to raise_error(Capybara::ElementNotFound, 'Unable to find xpath "//div[@id=\\"nosuchthing\\"]" that is a sibling of visible css "#child"')
end
end
| ruby | MIT | b3325b198464b806f07ec2011ceb532d6d5cf4ab | 2026-01-04T15:38:10.098638Z | false |
teamcapybara/capybara | https://github.com/teamcapybara/capybara/blob/b3325b198464b806f07ec2011ceb532d6d5cf4ab/lib/capybara/spec/session/accept_prompt_spec.rb | lib/capybara/spec/session/accept_prompt_spec.rb | # frozen_string_literal: true
Capybara::SpecHelper.spec '#accept_prompt', requires: [:modals] do
before do
@session.visit('/with_js')
end
it 'should accept the prompt with no message' do
@session.accept_prompt do
@session.click_link('Open prompt')
end
expect(@session).to have_xpath("//a[@id='open-prompt' and @response='']")
end
it 'should accept the prompt with no message when there is a default' do
@session.accept_prompt do
@session.click_link('Open defaulted prompt')
end
expect(@session).to have_xpath("//a[@id='open-prompt-with-default' and @response='Default value!']")
end
it 'should return the message presented' do
message = @session.accept_prompt do
@session.click_link('Open prompt')
end
expect(message).to eq('Prompt opened')
end
it 'should accept the prompt with a response' do
@session.accept_prompt with: 'the response' do
@session.click_link('Open prompt')
end
expect(@session).to have_xpath("//a[@id='open-prompt' and @response='the response']")
end
it 'should accept the prompt with a response when there is a default' do
@session.accept_prompt with: 'the response' do
@session.click_link('Open defaulted prompt')
end
expect(@session).to have_xpath("//a[@id='open-prompt-with-default' and @response='the response']")
end
it 'should accept the prompt with a blank response when there is a default' do
@session.accept_prompt with: '' do
@session.click_link('Open defaulted prompt')
end
expect(@session).to have_xpath("//a[@id='open-prompt-with-default' and @response='']")
end
it 'should allow special characters in the reponse' do
@session.accept_prompt with: '\'the\' \b "response"' do
@session.click_link('Open prompt')
end
expect(@session).to have_xpath(%{//a[@id='open-prompt' and @response=concat("'the' ", '\\b "response"')]})
end
it 'should accept the prompt if the message matches' do
@session.accept_prompt 'Prompt opened', with: 'matched' do
@session.click_link('Open prompt')
end
expect(@session).to have_xpath("//a[@id='open-prompt' and @response='matched']")
end
it "should not accept the prompt if the message doesn't match" do
expect do
@session.accept_prompt 'Incorrect Text', with: 'not matched' do
@session.click_link('Open prompt')
end
end.to raise_error(Capybara::ModalNotFound)
end
it 'should return the message presented' do
message = @session.accept_prompt with: 'the response' do
@session.click_link('Open prompt')
end
expect(message).to eq('Prompt opened')
end
end
| ruby | MIT | b3325b198464b806f07ec2011ceb532d6d5cf4ab | 2026-01-04T15:38:10.098638Z | false |
teamcapybara/capybara | https://github.com/teamcapybara/capybara/blob/b3325b198464b806f07ec2011ceb532d6d5cf4ab/lib/capybara/spec/session/accept_alert_spec.rb | lib/capybara/spec/session/accept_alert_spec.rb | # frozen_string_literal: true
Capybara::SpecHelper.spec '#accept_alert', requires: [:modals] do
before do
@session.visit('/with_js')
end
it 'should accept the alert' do
@session.accept_alert do
@session.click_link('Open alert')
end
expect(@session).to have_xpath("//a[@id='open-alert' and @opened='true']")
end
it 'should accept the alert if the text matches' do
@session.accept_alert 'Alert opened' do
@session.click_link('Open alert')
end
expect(@session).to have_xpath("//a[@id='open-alert' and @opened='true']")
end
it 'should accept the alert if text contains "special" Regex characters' do
@session.accept_alert 'opened [*Yay?*]' do
@session.click_link('Open alert')
end
expect(@session).to have_xpath("//a[@id='open-alert' and @opened='true']")
end
it 'should accept the alert if the text matches a regexp' do
@session.accept_alert(/op.{2}ed/) do
@session.click_link('Open alert')
end
expect(@session).to have_xpath("//a[@id='open-alert' and @opened='true']")
end
it 'should not accept the alert if the text doesnt match' do
expect do
@session.accept_alert 'Incorrect Text' do
@session.click_link('Open alert')
end
end.to raise_error(Capybara::ModalNotFound)
end
it 'should return the message presented' do
message = @session.accept_alert do
@session.click_link('Open alert')
end
expect(message).to eq('Alert opened [*Yay?*]')
end
it 'should handle the alert if the page changes' do
@session.accept_alert do
@session.click_link('Alert page change')
sleep 1 # ensure page change occurs before the accept_alert block exits
end
expect(@session).to have_current_path('/with_html', wait: 5)
end
context 'with an asynchronous alert' do
it 'should accept the alert' do
@session.accept_alert do
@session.click_link('Open delayed alert')
end
expect(@session).to have_xpath("//a[@id='open-delayed-alert' and @opened='true']")
end
it 'should return the message presented' do
message = @session.accept_alert do
@session.click_link('Open delayed alert')
end
expect(message).to eq('Delayed alert opened')
end
it 'should allow to adjust the delay' do
@session.accept_alert wait: 10 do
@session.click_link('Open slow alert')
end
expect(@session).to have_xpath("//a[@id='open-slow-alert' and @opened='true']")
end
end
end
| ruby | MIT | b3325b198464b806f07ec2011ceb532d6d5cf4ab | 2026-01-04T15:38:10.098638Z | false |
teamcapybara/capybara | https://github.com/teamcapybara/capybara/blob/b3325b198464b806f07ec2011ceb532d6d5cf4ab/lib/capybara/spec/session/click_link_spec.rb | lib/capybara/spec/session/click_link_spec.rb | # frozen_string_literal: true
Capybara::SpecHelper.spec '#click_link' do
before do
@session.visit('/with_html')
end
it 'should wait for asynchronous load', requires: [:js] do
Capybara.default_max_wait_time = 2
@session.visit('/with_js')
@session.click_link('Click me')
@session.click_link('Has been clicked')
end
it 'casts to string' do
@session.click_link(:foo)
expect(@session).to have_content('Another World')
end
it 'raises any errors caught inside the server', requires: [:server] do
quietly { @session.visit('/error') }
expect do
@session.click_link('foo')
end.to raise_error(TestApp::TestAppError)
end
context 'with id given' do
it 'should take user to the linked page' do
@session.click_link('foo')
expect(@session).to have_content('Another World')
end
end
context 'with text given' do
it 'should take user to the linked page' do
@session.click_link('labore')
expect(@session).to have_content('Bar')
end
it 'should accept partial matches', :exact_false do
@session.click_link('abo')
expect(@session).to have_content('Bar')
end
end
context 'with title given' do
it 'should take user to the linked page' do
@session.click_link('awesome title')
expect(@session).to have_content('Bar')
end
it 'should accept partial matches', :exact_false do
@session.click_link('some titl')
expect(@session).to have_content('Bar')
end
end
context 'with alternative text given to a contained image' do
it 'should take user to the linked page' do
@session.click_link('awesome image')
expect(@session).to have_content('Bar')
end
it 'should accept partial matches', :exact_false do
@session.click_link('some imag')
expect(@session).to have_content('Bar')
end
end
context "with a locator that doesn't exist" do
it 'should raise an error' do
msg = 'Unable to find link "does not exist"'
expect do
@session.click_link('does not exist')
end.to raise_error(Capybara::ElementNotFound, msg)
end
end
context 'with :href option given' do
it 'should find links with valid href' do
@session.click_link('labore', href: '/with_simple_html')
expect(@session).to have_content('Bar')
end
it "should raise error if link wasn't found" do
expect { @session.click_link('labore', href: 'invalid_href') }.to raise_error(Capybara::ElementNotFound, /with href "invalid_href/)
end
end
context 'with a regex :href option given' do
it 'should find a link matching an all-matching regex pattern' do
@session.click_link('labore', href: /.+/)
expect(@session).to have_content('Bar')
end
it 'should find a link matching an exact regex pattern' do
@session.click_link('labore', href: %r{/with_simple_html})
expect(@session).to have_content('Bar')
end
it 'should find a link matching a partial regex pattern' do
@session.click_link('labore', href: %r{/with_simple})
expect(@session).to have_content('Bar')
end
it "should raise an error if no link's href matched the pattern" do
expect { @session.click_link('labore', href: /invalid_pattern/) }.to raise_error(Capybara::ElementNotFound, %r{with href matching /invalid_pattern/})
expect { @session.click_link('labore', href: /.+d+/) }.to raise_error(Capybara::ElementNotFound, /#{Regexp.quote 'with href matching /.+d+/'}/)
end
context 'href: nil' do
it 'should not raise an error on links with no href attribute' do
expect { @session.click_link('No Href', href: nil) }.not_to raise_error
end
it 'should raise an error if href attribute exists' do
expect { @session.click_link('Blank Href', href: nil) }.to raise_error(Capybara::ElementNotFound, /with no href attribute/)
expect { @session.click_link('Normal Anchor', href: nil) }.to raise_error(Capybara::ElementNotFound, /with no href attribute/)
end
end
context 'href: false' do
it 'should not raise an error on links with no href attribute' do
expect { @session.click_link('No Href', href: false) }.not_to raise_error
end
it 'should not raise an error if href attribute exists' do
expect { @session.click_link('Blank Href', href: false) }.not_to raise_error
expect { @session.click_link('Normal Anchor', href: false) }.not_to raise_error
end
end
end
context 'with :target option given' do
it 'should find links with valid target' do
@session.click_link('labore', target: '_self')
expect(@session).to have_content('Bar')
end
it "should raise error if link wasn't found" do
expect { @session.click_link('labore', target: '_blank') }.to raise_error(Capybara::ElementNotFound, /Unable to find link "labore"/)
end
end
it 'should follow relative links' do
@session.visit('/')
@session.click_link('Relative')
expect(@session).to have_content('This is a test')
end
it 'should follow protocol relative links' do
@session.click_link('Protocol')
expect(@session).to have_content('Another World')
end
it 'should follow redirects' do
@session.click_link('Redirect')
expect(@session).to have_content('You landed')
end
it 'should follow redirects back to itself' do
@session.click_link('BackToMyself')
expect(@session).to have_css('#referrer', text: %r{/with_html$})
expect(@session).to have_content('This is a test')
end
it 'should add query string to current URL with naked query string' do
@session.click_link('Naked Query String')
expect(@session).to have_content('Query String sent')
end
it 'should do nothing on anchor links' do
@session.fill_in('test_field', with: 'blah')
@session.click_link('Normal Anchor')
expect(@session.find_field('test_field').value).to eq('blah')
@session.click_link('Blank Anchor')
expect(@session.find_field('test_field').value).to eq('blah')
@session.click_link('Blank JS Anchor')
expect(@session.find_field('test_field').value).to eq('blah')
end
it 'should do nothing on URL+anchor links for the same page' do
@session.fill_in('test_field', with: 'blah')
@session.click_link('Anchor on same page')
expect(@session.find_field('test_field').value).to eq('blah')
end
it 'should follow link on URL+anchor links for a different page' do
@session.click_link('Anchor on different page')
expect(@session).to have_content('Bar')
end
it 'should follow link on anchor if the path has regex special characters' do
@session.visit('/with.*html')
@session.click_link('Anchor on different page')
expect(@session).to have_content('Bar')
end
it 'should raise an error with links with no href' do
expect do
@session.click_link('No Href')
end.to raise_error(Capybara::ElementNotFound)
end
context 'with :exact option' do
it 'should accept partial matches when false' do
@session.click_link('abo', exact: false)
expect(@session).to have_content('Bar')
end
it 'should not accept partial matches when true' do
expect do
@session.click_link('abo', exact: true)
end.to raise_error(Capybara::ElementNotFound)
end
end
context 'without locator' do
it 'uses options' do
@session.click_link(href: '/foo')
expect(@session).to have_content('Another World')
end
end
it 'should return element clicked' do
el = @session.find(:link, 'Normal Anchor')
expect(@session.click_link('Normal Anchor')).to eq el
end
it 'can download a file', requires: [:download] do
# This requires the driver used for the test to be configured
# to download documents with the mime type "text/csv"
download_file = File.join(Capybara.save_path, 'download.csv')
expect(File).not_to exist(download_file)
@session.click_link('Download Me')
sleep 2 # allow time for file to download
expect(File).to exist(download_file)
FileUtils.rm_rf download_file
end
end
| ruby | MIT | b3325b198464b806f07ec2011ceb532d6d5cf4ab | 2026-01-04T15:38:10.098638Z | false |
teamcapybara/capybara | https://github.com/teamcapybara/capybara/blob/b3325b198464b806f07ec2011ceb532d6d5cf4ab/lib/capybara/spec/session/has_all_selectors_spec.rb | lib/capybara/spec/session/has_all_selectors_spec.rb | # frozen_string_literal: true
Capybara::SpecHelper.spec '#have_all_of_selectors' do
before do
@session.visit('/with_html')
end
it 'should be true if the given selectors are on the page' do
expect(@session).to have_all_of_selectors(:css, 'p a#foo', 'h2#h2one', 'h2#h2two')
end
it 'should be false if any of the given selectors are not on the page' do
expect do
expect(@session).to have_all_of_selectors(:css, 'p a#foo', 'h2#h2three', 'h2#h2one')
end.to raise_error RSpec::Expectations::ExpectationNotMetError
end
it 'should use default selector' do
Capybara.default_selector = :css
expect(@session).to have_all_of_selectors('p a#foo', 'h2#h2two', 'h2#h2one')
expect do
expect(@session).to have_all_of_selectors('p a#foo', 'h2#h2three', 'h2#h2one')
end.to raise_error RSpec::Expectations::ExpectationNotMetError
end
context 'should respect scopes' do
it 'when used with `within`' do
@session.within "//p[@id='first']" do
expect(@session).to have_all_of_selectors(".//a[@id='foo']")
expect do
expect(@session).to have_all_of_selectors(".//a[@id='red']")
end.to raise_error RSpec::Expectations::ExpectationNotMetError
end
end
it 'when called on elements' do
el = @session.find "//p[@id='first']"
expect(el).to have_all_of_selectors(".//a[@id='foo']")
expect do
expect(el).to have_all_of_selectors(".//a[@id='red']")
end.to raise_error RSpec::Expectations::ExpectationNotMetError
end
end
context 'with options' do
it 'should apply options to all locators' do
expect(@session).to have_all_of_selectors(:field, 'normal', 'additional_newline', type: :textarea)
expect do
expect(@session).to have_all_of_selectors(:field, 'normal', 'test_field', 'additional_newline', type: :textarea)
end.to raise_error RSpec::Expectations::ExpectationNotMetError
end
end
context 'with wait', requires: [:js] do
it 'should not raise error if all the elements appear before given wait duration' do
Capybara.using_wait_time(0.1) do
@session.visit('/with_js')
@session.click_link('Click me')
expect(@session).to have_all_of_selectors(:css, 'a#clickable', 'a#has-been-clicked', '#drag', wait: 5)
end
end
end
it 'cannot be negated' do
expect do
expect(@session).not_to have_all_of_selectors(:css, 'p a#foo', 'h2#h2one', 'h2#h2two')
end.to raise_error ArgumentError
end
end
| ruby | MIT | b3325b198464b806f07ec2011ceb532d6d5cf4ab | 2026-01-04T15:38:10.098638Z | false |
teamcapybara/capybara | https://github.com/teamcapybara/capybara/blob/b3325b198464b806f07ec2011ceb532d6d5cf4ab/lib/capybara/spec/session/has_element_spec.rb | lib/capybara/spec/session/has_element_spec.rb | # frozen_string_literal: true
Capybara::SpecHelper.spec '#has_element?' do
before do
@session.visit('/with_html')
end
it 'should be true if the given element is on the page' do
expect(@session).to have_element('a', id: 'foo')
expect(@session).to have_element('a', text: 'A link', href: '/with_simple_html')
# Should `text` actually accept a symbol?
# expect(@session).to have_element('a', text: :'A link', href: :'/with_simple_html')
expect(@session).to have_element('a', text: 'A link', href: %r{/with_simple_html})
expect(@session).to have_element('a', text: 'labore', target: '_self')
end
it 'should be false if the given element is not on the page' do
expect(@session).not_to have_element('a', text: 'monkey')
expect(@session).not_to have_element('a', text: 'A link', href: '/nonexistent-href')
expect(@session).not_to have_element('a', text: 'A link', href: /nonexistent/)
expect(@session).not_to have_element('a', text: 'labore', target: '_blank')
end
it 'should notify if an invalid locator is specified' do
allow(Capybara::Helpers).to receive(:warn).and_return(nil)
@session.has_element?(@session)
expect(Capybara::Helpers).to have_received(:warn).with(/Called from: .+/)
end
end
Capybara::SpecHelper.spec '#has_no_element?' do
before do
@session.visit('/with_html')
end
it 'should be false if the given element is on the page' do
expect(@session).not_to have_no_element('a', id: 'foo')
expect(@session).not_to have_no_element('a', text: 'A link', href: '/with_simple_html')
expect(@session).not_to have_no_element('a', text: 'labore', target: '_self')
end
it 'should be true if the given element is not on the page' do
expect(@session).to have_no_element('a', text: 'monkey')
expect(@session).to have_no_element('a', text: 'A link', href: '/nonexistent-href')
expect(@session).to have_no_element('a', text: 'A link', href: %r{/nonexistent-href})
expect(@session).to have_no_element('a', text: 'labore', target: '_blank')
end
end
| ruby | MIT | b3325b198464b806f07ec2011ceb532d6d5cf4ab | 2026-01-04T15:38:10.098638Z | false |
teamcapybara/capybara | https://github.com/teamcapybara/capybara/blob/b3325b198464b806f07ec2011ceb532d6d5cf4ab/lib/capybara/spec/session/save_screenshot_spec.rb | lib/capybara/spec/session/save_screenshot_spec.rb | # frozen_string_literal: true
Capybara::SpecHelper.spec '#save_screenshot', requires: [:screenshot] do
let(:alternative_path) { File.join(Dir.pwd, 'save_screenshot_tmp') }
before do
@old_save_path = Capybara.save_path
Capybara.save_path = nil
@session.visit '/foo'
end
after do
Capybara.save_path = @old_save_path
FileUtils.rm_rf alternative_path
end
it 'generates sensible filename' do
allow(@session.driver).to receive(:save_screenshot)
@session.save_screenshot
regexp = Regexp.new(File.join(Dir.pwd, 'capybara-\d+\.png'))
expect(@session.driver).to have_received(:save_screenshot).with(regexp, any_args)
end
it 'allows to specify another path' do
allow(@session.driver).to receive(:save_screenshot)
custom_path = 'screenshots/1.png'
@session.save_screenshot(custom_path)
expect(@session.driver).to have_received(:save_screenshot).with(/#{custom_path}$/, any_args)
end
context 'with Capybara.save_path' do
it 'file is generated in the correct location' do
Capybara.save_path = alternative_path
allow(@session.driver).to receive(:save_screenshot)
@session.save_screenshot
regexp = Regexp.new(File.join(alternative_path, 'capybara-\d+\.png'))
expect(@session.driver).to have_received(:save_screenshot).with(regexp, any_args)
end
it 'relative paths are relative to save_path' do
Capybara.save_path = alternative_path
allow(@session.driver).to receive(:save_screenshot)
custom_path = 'screenshots/2.png'
@session.save_screenshot(custom_path)
expect(@session.driver).to have_received(:save_screenshot).with(File.expand_path(custom_path, alternative_path), any_args)
end
end
end
| ruby | MIT | b3325b198464b806f07ec2011ceb532d6d5cf4ab | 2026-01-04T15:38:10.098638Z | false |
teamcapybara/capybara | https://github.com/teamcapybara/capybara/blob/b3325b198464b806f07ec2011ceb532d6d5cf4ab/lib/capybara/spec/session/node_spec.rb | lib/capybara/spec/session/node_spec.rb | # frozen_string_literal: true
# NOTE: This file uses `sleep` to sync up parts of the tests. This is only implemented like this
# because of the methods being tested. In tests using Capybara this type of behavior should be implemented
# using Capybara provided assertions with builtin waiting behavior.
Capybara::SpecHelper.spec 'node' do
before do
@session.visit('/with_html')
end
it 'should act like a session object' do
@session.visit('/form')
@form = @session.find(:css, '#get-form')
expect(@form).to have_field('Middle Name')
expect(@form).to have_no_field('Languages')
@form.fill_in('Middle Name', with: 'Monkey')
@form.click_button('med')
expect(extract_results(@session)['middle_name']).to eq('Monkey')
end
it 'should scope CSS selectors' do
expect(@session.find(:css, '#second')).to have_no_css('h1')
end
describe '#query_scope' do
it 'should have a reference to the element the query was evaluated on if there is one' do
node = @session.find(:css, '#first')
expect(node.query_scope).to eq(node.session.document)
expect(node.find(:css, '#foo').query_scope).to eq(node)
end
end
describe '#text' do
it 'should extract node texts' do
expect(@session.all('//a')[0].text).to eq('labore')
expect(@session.all('//a')[1].text).to eq('ullamco')
end
it 'should return document text on /html selector' do
@session.visit('/with_simple_html')
expect(@session.all('/html')[0].text).to eq('Bar')
end
end
describe '#[]' do
it 'should extract node attributes' do
expect(@session.all('//a')[0][:class]).to eq('simple')
expect(@session.all('//a')[1][:id]).to eq('foo')
expect(@session.all('//input')[0][:type]).to eq('text')
end
it 'should extract boolean node attributes' do
expect(@session.find('//input[@id="checked_field"]')[:checked]).to be_truthy
end
end
describe '#style', requires: [:css] do
it 'should return the computed style value' do
expect(@session.find(:css, '#first').style('display')).to eq('display' => 'block')
expect(@session.find(:css, '#second').style(:display)).to eq('display' => 'inline')
end
it 'should return multiple style values' do
expect(@session.find(:css, '#first').style('display', :'line-height')).to eq('display' => 'block', 'line-height' => '25px')
end
end
describe '#value' do
it 'should allow retrieval of the value' do
expect(@session.find('//textarea[@id="normal"]').value).to eq('banana')
end
it 'should not swallow extra newlines in textarea' do
expect(@session.find('//textarea[@id="additional_newline"]').value).to eq("\nbanana")
end
it 'should not swallow leading newlines for set content in textarea' do
@session.find('//textarea[@id="normal"]').set("\nbanana")
expect(@session.find('//textarea[@id="normal"]').value).to eq("\nbanana")
end
it 'return any HTML content in textarea' do
@session.find('//textarea[1]').set('some <em>html</em> here')
expect(@session.find('//textarea[1]').value).to eq('some <em>html</em> here')
end
it "defaults to 'on' for checkbox" do
@session.visit('/form')
expect(@session.find('//input[@id="valueless_checkbox"]').value).to eq('on')
end
it "defaults to 'on' for radio buttons" do
@session.visit('/form')
expect(@session.find('//input[@id="valueless_radio"]').value).to eq('on')
end
end
describe '#set' do
it 'should allow assignment of field value' do
expect(@session.first('//input').value).to eq('monkey')
@session.first('//input').set('gorilla')
expect(@session.first('//input').value).to eq('gorilla')
end
it 'should fill the field even if the caret was not at the end', requires: [:js] do
@session.execute_script("var el = document.getElementById('test_field'); el.focus(); el.setSelectionRange(0, 0);")
@session.first('//input').set('')
expect(@session.first('//input').value).to eq('')
end
if ENV['CAPYBARA_THOROUGH']
it 'should raise if the text field is readonly' do
expect { @session.first('//input[@readonly]').set('changed') }.to raise_error(Capybara::ReadOnlyElementError)
end
it 'should raise if the textarea is readonly' do
expect { @session.first('//textarea[@readonly]').set('changed') }.to raise_error(Capybara::ReadOnlyElementError)
end
else
it 'should not change if the text field is readonly' do
@session.first('//input[@readonly]').set('changed')
expect(@session.first('//input[@readonly]').value).to eq 'should not change'
end
it 'should not change if the textarea is readonly' do
@session.first('//textarea[@readonly]').set('changed')
expect(@session.first('//textarea[@readonly]').value).to eq 'textarea should not change'
end
end
it 'should use global default options' do
Capybara.default_set_options = { clear: :backspace }
element = @session.first(:fillable_field, type: 'text')
allow(element.base).to receive(:set)
element.set('gorilla')
expect(element.base).to have_received(:set).with('gorilla', clear: :backspace)
end
context 'with a contenteditable element', requires: [:js] do
it 'should allow me to change the contents' do
@session.visit('/with_js')
@session.find(:css, '#existing_content_editable').set('WYSIWYG')
expect(@session.find(:css, '#existing_content_editable').text).to eq('WYSIWYG')
end
it 'should allow me to set the contents' do
@session.visit('/with_js')
@session.find(:css, '#blank_content_editable').set('WYSIWYG')
expect(@session.find(:css, '#blank_content_editable').text).to eq('WYSIWYG')
end
it 'should allow me to change the contents of a child element' do
@session.visit('/with_js')
@session.find(:css, '#existing_content_editable_child').set('WYSIWYG')
expect(@session.find(:css, '#existing_content_editable_child').text).to eq('WYSIWYG')
expect(@session.find(:css, '#existing_content_editable_child_parent').text).to eq("Some content\nWYSIWYG")
end
end
it 'should submit single text input forms if ended with \n' do
@session.visit('/form')
@session.find(:css, '#single_input').set("my entry\n")
expect(extract_results(@session)['single_input']).to eq('my entry')
end
it 'should not submit single text input forms if ended with \n and has multiple values' do
@session.visit('/form')
@session.find(:css, '#two_input_1').set("my entry\n")
expect(@session.find(:css, '#two_input_1').value).to eq("my entry\n").or(eq 'my entry')
end
end
describe '#tag_name' do
it 'should extract node tag name' do
expect(@session.all('//a')[0].tag_name).to eq('a')
expect(@session.all('//a')[1].tag_name).to eq('a')
expect(@session.all('//p')[1].tag_name).to eq('p')
end
end
describe '#disabled?' do
it 'should extract disabled node' do
@session.visit('/form')
expect(@session.find('//input[@id="customer_name"]')).to be_disabled
expect(@session.find('//input[@id="customer_email"]')).not_to be_disabled
end
it 'should see disabled options as disabled' do
@session.visit('/form')
expect(@session.find('//select[@id="form_title"]/option[1]')).not_to be_disabled
expect(@session.find('//select[@id="form_title"]/option[@disabled]')).to be_disabled
end
it 'should see enabled options in disabled select as disabled' do
@session.visit('/form')
expect(@session.find('//select[@id="form_disabled_select"]/option')).to be_disabled
expect(@session.find('//select[@id="form_disabled_select"]/optgroup/option')).to be_disabled
expect(@session.find('//select[@id="form_title"]/option[1]')).not_to be_disabled
end
it 'should see enabled options in disabled optgroup as disabled' do
@session.visit('/form')
expect(@session.find('//option', text: 'A.B.1')).to be_disabled
expect(@session.find('//option', text: 'A.2')).not_to be_disabled
end
it 'should see a disabled fieldset as disabled' do
@session.visit('/form')
expect(@session.find(:xpath, './/fieldset[@id="form_disabled_fieldset"]')).to be_disabled
end
context 'in a disabled fieldset' do
# https://html.spec.whatwg.org/#the-fieldset-element
it 'should see elements not in first legend as disabled' do
@session.visit('/form')
expect(@session.find('//input[@id="form_disabled_fieldset_child"]')).to be_disabled
expect(@session.find('//input[@id="form_disabled_fieldset_second_legend_child"]')).to be_disabled
expect(@session.find('//input[@id="form_enabled_fieldset_child"]')).not_to be_disabled
end
it 'should see elements in first legend as enabled' do
@session.visit('/form')
expect(@session.find('//input[@id="form_disabled_fieldset_legend_child"]')).not_to be_disabled
end
it 'should sees options not in first legend as disabled' do
@session.visit('/form')
expect(@session.find('//option', text: 'Disabled Child Option')).to be_disabled
end
end
it 'should be boolean' do
@session.visit('/form')
expect(@session.find('//select[@id="form_disabled_select"]/option').disabled?).to be true
expect(@session.find('//select[@id="form_disabled_select2"]/option').disabled?).to be true
expect(@session.find('//select[@id="form_title"]/option[1]').disabled?).to be false
end
it 'should be disabled for all elements that are CSS :disabled' do
@session.visit('/form')
# sanity check
expect(@session.all(:css, ':disabled')).to all(be_disabled)
end
end
describe '#visible?' do
before { Capybara.ignore_hidden_elements = false }
it 'should extract node visibility' do
expect(@session.first('//a')).to be_visible
expect(@session.find('//div[@id="hidden"]')).not_to be_visible
expect(@session.find('//div[@id="hidden_via_ancestor"]')).not_to be_visible
expect(@session.find('//div[@id="hidden_attr"]')).not_to be_visible
expect(@session.find('//a[@id="hidden_attr_via_ancestor"]')).not_to be_visible
expect(@session.find('//input[@id="hidden_input"]')).not_to be_visible
end
it 'template elements should not be visible' do
expect(@session.find('//template')).not_to be_visible
end
it 'should be boolean' do
expect(@session.first('//a').visible?).to be true
expect(@session.find('//div[@id="hidden"]').visible?).to be false
end
it 'closed details > summary elements and descendants should be visible' do
expect(@session.find(:css, '#closed_details summary')).to be_visible
expect(@session.find(:css, '#closed_details summary h6')).to be_visible
end
it 'details non-summary descendants should be non-visible when closed' do
descendants = @session.all(:css, '#closed_details > *:not(summary), #closed_details > *:not(summary) *', minimum: 2)
expect(descendants).not_to include(be_visible)
end
it 'deatils descendants should be visible when open' do
descendants = @session.all(:css, '#open_details *')
expect(descendants).to all(be_visible)
end
it 'works when details is toggled open and closed' do
@session.find(:css, '#closed_details > summary').click
expect(@session).to have_css('#closed_details *', visible: :visible, count: 5)
.and(have_no_css('#closed_details *', visible: :hidden))
@session.find(:css, '#closed_details > summary').click
descendants_css = '#closed_details > *:not(summary), #closed_details > *:not(summary) *'
expect(@session).to have_no_css(descendants_css, visible: :visible)
.and(have_css(descendants_css, visible: :hidden, count: 3))
sleep 20
end
it 'works with popover attribute' do
expect(@session.find(:button, 'Should not be clickable')).not_to be_visible
expect(@session.find(:button, 'Should be clickable')).not_to be_visible
@session.click_button('Show popover')
expect(@session.find(:button, 'Should be clickable')).to be_visible
expect(@session.find(:button, 'Should not be clickable')).not_to be_visible
end
it 'works with popover parents' do
expect(@session.find(:id, 'popover_parent')).not_to be_visible
expect(@session.find(:id, 'popover_child')).not_to be_visible
@session.click_button('Show parent popover')
expect(@session.find(:id, 'popover_child', text: 'Popover Contents')).to be_visible
end
end
describe '#obscured?', requires: [:css] do
it 'should see non visible elements as obscured' do
Capybara.ignore_hidden_elements = false
expect(@session.find('//div[@id="hidden"]')).to be_obscured
expect(@session.find('//div[@id="hidden_via_ancestor"]')).to be_obscured
expect(@session.find('//div[@id="hidden_attr"]')).to be_obscured
expect(@session.find('//a[@id="hidden_attr_via_ancestor"]')).to be_obscured
expect(@session.find('//input[@id="hidden_input"]')).to be_obscured
end
it 'should see non-overlapped elements as not obscured' do
@session.visit('/obscured')
expect(@session.find(:css, '#cover')).not_to be_obscured
end
it 'should see elements only overlapped by descendants as not obscured' do
skip 'Fails on CI, unsure why. Needs investigation.' if ENV['CI']
expect(@session.first(:css, 'p:not(.para)')).not_to be_obscured
end
it 'should see elements outside the viewport as obscured' do
@session.visit('/obscured')
off = @session.find(:css, '#offscreen')
off_wrapper = @session.find(:css, '#offscreen_wrapper')
expect(off).to be_obscured
expect(off_wrapper).to be_obscured
@session.scroll_to(off_wrapper)
expect(off_wrapper).not_to be_obscured
expect(off).to be_obscured
off_wrapper.scroll_to(off)
expect(off).not_to be_obscured
expect(off_wrapper).not_to be_obscured
end
it 'should see overlapped elements as obscured' do
@session.visit('/obscured')
expect(@session.find(:css, '#obscured')).to be_obscured
end
it 'should be boolean' do
Capybara.ignore_hidden_elements = false
expect(@session.first('//a').obscured?).to be false
expect(@session.find('//div[@id="hidden"]').obscured?).to be true
end
it 'should work in frames' do
@session.visit('/obscured')
frame = @session.find(:css, '#frameOne')
@session.within_frame(frame) do
div = @session.find(:css, '#divInFrameOne')
expect(div).to be_obscured
@session.scroll_to div
expect(div).not_to be_obscured
end
end
it 'should work in nested iframes' do
@session.visit('/obscured')
frame = @session.find(:css, '#nestedFrames')
@session.within_frame(frame) do
@session.within_frame(:css, '#childFrame') do
gcframe = @session.find(:css, '#grandchildFrame2')
@session.within_frame(gcframe) do
expect(@session.find(:css, '#divInFrameTwo')).to be_obscured
end
@session.scroll_to(gcframe)
@session.within_frame(gcframe) do
expect(@session.find(:css, '#divInFrameTwo')).not_to be_obscured
end
end
end
end
end
describe '#checked?' do
it 'should extract node checked state' do
@session.visit('/form')
expect(@session.find('//input[@id="gender_female"]')).to be_checked
expect(@session.find('//input[@id="gender_male"]')).not_to be_checked
expect(@session.first('//h1')).not_to be_checked
end
it 'should be boolean' do
@session.visit('/form')
expect(@session.find('//input[@id="gender_female"]').checked?).to be true
expect(@session.find('//input[@id="gender_male"]').checked?).to be false
expect(@session.find('//input[@id="no_attr_value_checked"]').checked?).to be true
end
end
describe '#selected?' do
it 'should extract node selected state' do
@session.visit('/form')
expect(@session.find('//option[@value="en"]')).to be_selected
expect(@session.find('//option[@value="sv"]')).not_to be_selected
expect(@session.first('//h1')).not_to be_selected
end
it 'should be boolean' do
@session.visit('/form')
expect(@session.find('//option[@value="en"]').selected?).to be true
expect(@session.find('//option[@value="sv"]').selected?).to be false
expect(@session.first('//h1').selected?).to be false
end
end
describe '#==' do
it 'preserve object identity' do
expect(@session.find('//h1') == @session.find('//h1')).to be true # rubocop:disable Lint/BinaryOperatorWithIdenticalOperands
expect(@session.find('//h1') === @session.find('//h1')).to be true # rubocop:disable Style/CaseEquality, Lint/BinaryOperatorWithIdenticalOperands
expect(@session.find('//h1').eql?(@session.find('//h1'))).to be false
end
it 'returns false for unrelated object' do
expect(@session.find('//h1') == 'Not Capybara::Node::Base').to be false
end
end
describe '#path' do
# Testing for specific XPaths here doesn't make sense since there
# are many that can refer to the same element
before do
@session.visit('/path')
end
it 'returns xpath which points to itself' do
element = @session.find(:link, 'Second Link')
expect(@session.find(:xpath, element.path)).to eq(element)
end
it 'reports when element in shadow dom', requires: [:shadow_dom] do
@session.visit('/with_js')
shadow = @session.find(:css, '#shadow')
element = @session.evaluate_script(<<~JS, shadow)
(function(root){
return root.shadowRoot.querySelector('span');
})(arguments[0])
JS
expect(element.path).to eq '(: Shadow DOM element - no XPath :)'
end
end
describe '#trigger', requires: %i[js trigger] do
it 'should allow triggering of custom JS events' do
@session.visit('/with_js')
@session.find(:css, '#with_focus_event').trigger(:focus)
expect(@session).to have_css('#focus_event_triggered')
end
end
describe '#drag_to', requires: %i[js drag] do
it 'should drag and drop an object' do
@session.visit('/with_js')
element = @session.find('//div[@id="drag"]')
target = @session.find('//div[@id="drop"]')
element.drag_to(target)
expect(@session).to have_xpath('//div[contains(., "Dropped!")]')
end
it 'should drag and drop if scrolling is needed' do
@session.visit('/with_js')
element = @session.find('//div[@id="drag_scroll"]')
target = @session.find('//div[@id="drop_scroll"]')
element.drag_to(target)
expect(@session).to have_xpath('//div[contains(., "Dropped!")]')
end
it 'should drag a link' do
@session.visit('/with_js')
link = @session.find_link('drag_link')
target = @session.find(:id, 'drop')
link.drag_to target
expect(@session).to have_xpath('//div[contains(., "Dropped!")]')
end
it 'should work with Dragula' do
@session.visit('/with_dragula')
@session.within(:css, '#sortable.ready') do
src = @session.find('div', text: 'Item 1')
target = @session.find('div', text: 'Item 3')
src.drag_to target
expect(@session).to have_content(/Item 2.*Item 1/, normalize_ws: true)
end
end
it 'should work with jsTree' do
@session.visit('/with_jstree')
@session.within(:css, '#container') do
@session.assert_text(/A.*B.*C/m)
source = @session.find(:css, '#j1_1_anchor')
target = @session.find(:css, '#j1_2_anchor')
source.drag_to(target)
@session.assert_no_text(/A.*B.*C/m)
@session.assert_text(/B.*C/m)
end
end
it 'should simulate a single held down modifier key' do
%I[
alt
ctrl
meta
shift
].each do |modifier_key|
@session.visit('/with_js')
element = @session.find('//div[@id="drag"]')
target = @session.find('//div[@id="drop"]')
element.drag_to(target, drop_modifiers: modifier_key)
expect(@session).to have_css('div.drag_start', exact_text: 'Dragged!')
expect(@session).to have_xpath("//div[contains(., 'Dropped!-#{modifier_key}')]")
end
end
it 'should simulate multiple held down modifier keys' do
@session.visit('/with_js')
element = @session.find('//div[@id="drag"]')
target = @session.find('//div[@id="drop"]')
modifier_keys = %I[alt ctrl meta shift]
element.drag_to(target, drop_modifiers: modifier_keys)
expect(@session).to have_xpath("//div[contains(., 'Dropped!-#{modifier_keys.join('-')}')]")
end
it 'should support key aliases' do
{ control: :ctrl,
command: :meta,
cmd: :meta }.each do |(key_alias, key)|
@session.visit('/with_js')
element = @session.find('//div[@id="drag"]')
target = @session.find('//div[@id="drop"]')
element.drag_to(target, drop_modifiers: [key_alias])
expect(target).to have_text("Dropped!-#{key}", exact: true)
end
end
context 'HTML5', requires: %i[js html5_drag] do
it 'should HTML5 drag and drop an object' do
@session.visit('/with_js')
element = @session.find('//div[@id="drag_html5"]')
target = @session.find('//div[@id="drop_html5"]')
element.drag_to(target)
expect(@session).to have_xpath('//div[contains(., "HTML5 Dropped string: text/plain drag_html5")]')
end
it 'should HTML5 drag and drop an object child' do
@session.visit('/with_js')
element = @session.find('//div[@id="drag_html5"]/p')
target = @session.find('//div[@id="drop_html5"]')
element.drag_to(target)
expect(@session).to have_xpath('//div[contains(., "HTML5 Dropped string: text/plain drag_html5")]')
end
it 'should set clientX/Y in dragover events' do
@session.visit('/with_js')
element = @session.find('//div[@id="drag_html5"]')
target = @session.find('//div[@id="drop_html5"]')
element.drag_to(target)
expect(@session).to have_css('div.log', text: /DragOver with client position: [1-9]\d*,[1-9]\d*/, count: 2)
end
it 'should preserve clientX/Y from last dragover event' do
@session.visit('/with_js')
element = @session.find('//div[@id="drag_html5"]')
target = @session.find('//div[@id="drop_html5"]')
element.drag_to(target)
conditions = %w[DragLeave Drop DragEnd].map do |text|
have_css('div.log', text: text)
end
expect(@session).to(conditions.reduce { |memo, cond| memo.and(cond) })
# The first "DragOver" div is inserted by the last dragover event dispatched
drag_over_div = @session.first('//div[@class="log" and starts-with(text(), "DragOver")]')
position = drag_over_div.text.sub('DragOver ', '')
expect(@session).to have_css('div.log', text: /DragLeave #{position}/, count: 1)
expect(@session).to have_css('div.log', text: /Drop #{position}/, count: 1)
expect(@session).to have_css('div.log', text: /DragEnd #{position}/, count: 1)
end
it 'should not HTML5 drag and drop on a non HTML5 drop element' do
@session.visit('/with_js')
element = @session.find('//div[@id="drag_html5"]')
target = @session.find('//div[@id="drop_html5"]')
target.execute_script("$(this).removeClass('drop');")
element.drag_to(target)
sleep 1
expect(@session).not_to have_xpath('//div[contains(., "HTML5 Dropped")]')
end
it 'should HTML5 drag and drop when scrolling needed' do
@session.visit('/with_js')
element = @session.find('//div[@id="drag_html5_scroll"]')
target = @session.find('//div[@id="drop_html5_scroll"]')
element.drag_to(target)
expect(@session).to have_xpath('//div[contains(., "HTML5 Dropped string: text/plain drag_html5_scroll")]')
end
it 'should drag HTML5 default draggable elements' do
@session.visit('/with_js')
link = @session.find_link('drag_link_html5')
target = @session.find(:id, 'drop_html5')
link.drag_to target
expect(@session).to have_xpath('//div[contains(., "HTML5 Dropped")]')
end
it 'should work with SortableJS' do
@session.visit('/with_sortable_js')
@session.within(:css, '#sortable') do
src = @session.find('div', text: 'Item 1')
target = @session.find('div', text: 'Item 3')
src.drag_to target
expect(@session).to have_content(/Item 3.*Item 1/, normalize_ws: true)
end
end
it 'should drag HTML5 default draggable element child' do
@session.visit('/with_js')
source = @session.find_link('drag_link_html5').find(:css, 'p')
target = @session.find(:id, 'drop_html5')
source.drag_to target
expect(@session).to have_xpath('//div[contains(., "HTML5 Dropped")]')
end
it 'should simulate a single held down modifier key' do
%I[alt ctrl meta shift].each do |modifier_key|
@session.visit('/with_js')
element = @session.find('//div[@id="drag_html5"]')
target = @session.find('//div[@id="drop_html5"]')
element.drag_to(target, drop_modifiers: modifier_key)
expect(@session).to have_css('div.drag_start', exact_text: 'HTML5 Dragged!')
expect(@session).to have_xpath("//div[contains(., 'HTML5 Dropped string: text/plain drag_html5-#{modifier_key}')]")
end
end
it 'should simulate multiple held down modifier keys' do
@session.visit('/with_js')
element = @session.find('//div[@id="drag_html5"]')
target = @session.find('//div[@id="drop_html5"]')
modifier_keys = %I[alt ctrl meta shift]
element.drag_to(target, drop_modifiers: modifier_keys)
expect(@session).to have_xpath("//div[contains(., 'HTML5 Dropped string: text/plain drag_html5-#{modifier_keys.join('-')}')]")
end
it 'should support key aliases' do
{ control: :ctrl,
command: :meta,
cmd: :meta }.each do |(key_alias, key)|
@session.visit('/with_js')
element = @session.find('//div[@id="drag_html5"]')
target = @session.find('//div[@id="drop_html5"]')
element.drag_to(target, drop_modifiers: [key_alias])
expect(target).to have_text(%r{^HTML5 Dropped string: text/plain drag_html5-#{key}$}m, exact: true)
end
end
it 'should trigger a dragenter event, before the first dragover event' do
@session.visit('/with_js')
element = @session.find('//div[@id="drag_html5"]')
target = @session.find('//div[@id="drop_html5"]')
element.drag_to(target)
# Events are listed in reverse chronological order
expect(@session).to have_text(/DragOver.*DragEnter/m)
end
end
end
describe 'Element#drop', requires: %i[js html5_drag] do
it 'can drop a file' do
@session.visit('/with_js')
target = @session.find('//div[@id="drop_html5"]')
target.drop(
with_os_path_separators(File.expand_path('../fixtures/capybara.jpg', File.dirname(__FILE__)))
)
expect(@session).to have_xpath('//div[contains(., "HTML5 Dropped file: capybara.jpg")]')
end
it 'can drop multiple files' do
@session.visit('/with_js')
target = @session.find('//div[@id="drop_html5"]')
target.drop(
with_os_path_separators(File.expand_path('../fixtures/capybara.jpg', File.dirname(__FILE__))),
with_os_path_separators(File.expand_path('../fixtures/test_file.txt', File.dirname(__FILE__)))
)
expect(@session).to have_xpath('//div[contains(., "HTML5 Dropped file: capybara.jpg")]')
expect(@session).to have_xpath('//div[contains(., "HTML5 Dropped file: test_file.txt")]')
end
it 'can drop strings' do
@session.visit('/with_js')
target = @session.find('//div[@id="drop_html5"]')
target.drop('text/plain' => 'Some dropped text')
expect(@session).to have_xpath('//div[contains(., "HTML5 Dropped string: text/plain Some dropped text")]')
end
it 'can drop a pathname' do
@session.visit('/with_js')
target = @session.find('//div[@id="drop_html5"]')
target.drop(
Pathname.new(with_os_path_separators(File.expand_path('../fixtures/capybara.jpg', File.dirname(__FILE__))))
)
expect(@session).to have_xpath('//div[contains(., "HTML5 Dropped file: capybara.jpg")]')
end
it 'can drop multiple strings' do
@session.visit('/with_js')
target = @session.find('//div[@id="drop_html5"]')
target.drop('text/plain' => 'Some dropped text', 'text/url' => 'http://www.google.com')
expect(@session).to have_xpath('//div[contains(., "HTML5 Dropped string: text/plain Some dropped text")]')
expect(@session).to have_xpath('//div[contains(., "HTML5 Dropped string: text/url http://www.google.com")]')
end
end
describe '#hover', requires: [:hover] do
it 'should allow hovering on an element' do
@session.visit('/with_hover')
expect(@session.find(:css, '.wrapper:not(.scroll_needed) .hidden_until_hover', visible: false)).not_to be_visible
@session.find(:css, '.wrapper:not(.scroll_needed)').hover
expect(@session.find(:css, '.wrapper:not(.scroll_needed) .hidden_until_hover', visible: false)).to be_visible
end
it 'should allow hovering on an element that needs to be scrolled into view' do
@session.visit('/with_hover')
expect(@session.find(:css, '.wrapper.scroll_needed .hidden_until_hover', visible: false)).not_to be_visible
@session.find(:css, '.wrapper.scroll_needed').hover
expect(@session.find(:css, '.wrapper.scroll_needed .hidden_until_hover', visible: false)).to be_visible
end
it 'should hover again after following a link and back' do
@session.visit('/with_hover')
@session.find(:css, '.wrapper:not(.scroll_needed)').hover
@session.click_link('Other hover page')
@session.click_link('Go back')
@session.find(:css, '.wrapper:not(.scroll_needed)').hover
expect(@session.find(:css, '.wrapper:not(.scroll_needed) .hidden_until_hover', visible: false)).to be_visible
end
end
describe '#click' do
it 'should not follow a link if no href' do
@session.find(:css, '#link_placeholder').click
expect(@session.current_url).to match(%r{/with_html$})
end
it 'should go to the same page if href is blank' do
@session.find(:css, '#link_blank_href').click
sleep 1
expect(@session).to have_current_path('/with_html')
end
it 'should be able to check a checkbox' do
@session.visit('form')
cbox = @session.find(:checkbox, 'form_terms_of_use')
expect(cbox).not_to be_checked
cbox.click
expect(cbox).to be_checked
end
it 'should be able to uncheck a checkbox' do
@session.visit('/form')
cbox = @session.find(:checkbox, 'form_pets_dog')
expect(cbox).to be_checked
cbox.click
expect(cbox).not_to be_checked
end
it 'should be able to select a radio button' do
@session.visit('/form')
radio = @session.find(:radio_button, 'gender_male')
expect(radio).not_to be_checked
radio.click
expect(radio).to be_checked
end
it 'should allow modifiers', requires: [:js] do
@session.visit('/with_js')
@session.find(:css, '#click-test').click(:shift)
expect(@session).to have_link('Has been shift clicked')
end
it 'should allow multiple modifiers', requires: [:js] do
@session.visit('with_js')
@session.find(:css, '#click-test').click(:control, :alt, :meta, :shift)
# Selenium with Chrome on OSX ctrl-click generates a right click so just verify all keys but not click type
expect(@session).to have_link('alt control meta shift')
end
it 'should allow to adjust the click offset', requires: [:js] do
Capybara.w3c_click_offset = false
@session.visit('with_js')
@session.find(:css, '#click-test').click(x: 5, y: 5)
link = @session.find(:link, 'has-been-clicked')
locations = link.text.match(/^Has been clicked at (?<x>[\d.-]+),(?<y>[\d.-]+)$/)
| ruby | MIT | b3325b198464b806f07ec2011ceb532d6d5cf4ab | 2026-01-04T15:38:10.098638Z | true |
teamcapybara/capybara | https://github.com/teamcapybara/capybara/blob/b3325b198464b806f07ec2011ceb532d6d5cf4ab/lib/capybara/spec/session/has_current_path_spec.rb | lib/capybara/spec/session/has_current_path_spec.rb | # frozen_string_literal: true
Capybara::SpecHelper.spec '#has_current_path?' do
before do
@session.visit('/with_js')
end
it 'should be true if the page has the given current path' do
expect(@session).to have_current_path('/with_js')
end
it 'should allow regexp matches' do
expect(@session).to have_current_path(/w[a-z]{3}_js/)
expect(@session).not_to have_current_path(/monkey/)
end
it 'should not raise an error when non-http' do
@session.reset_session!
expect(@session.has_current_path?(/monkey/)).to be false
expect(@session.has_current_path?('/with_js')).to be false
end
it 'should handle non-escaped query options' do
@session.click_link('Non-escaped query options')
expect(@session).to have_current_path('/with_html?options[]=things')
end
it 'should handle escaped query options' do
@session.click_link('Escaped query options')
expect(@session).to have_current_path('/with_html?options%5B%5D=things')
end
it 'should wait for current_path', requires: [:js] do
@session.click_link('Change page')
expect(@session).to have_current_path('/with_html', wait: 3)
end
it 'should be false if the page has not the given current_path' do
expect(@session).not_to have_current_path('/with_html')
end
it 'should check query options' do
@session.visit('/with_js?test=test')
expect(@session).to have_current_path('/with_js?test=test')
end
it 'should compare the full url if url: true is used' do
expect(@session).to have_current_path(%r{\Ahttp://[^/]*/with_js\Z}, url: true)
domain_port = if @session.respond_to?(:server) && @session.server
"#{@session.server.host}:#{@session.server.port}"
else
'www.example.com'
end
expect(@session).to have_current_path("http://#{domain_port}/with_js", url: true)
end
it 'should not compare the full url if url: true is not passed' do
expect(@session).to have_current_path(%r{^/with_js\Z})
expect(@session).to have_current_path('/with_js')
end
it 'should not compare the full url if url: false is passed' do
expect(@session).to have_current_path(%r{^/with_js\Z}, url: false)
expect(@session).to have_current_path('/with_js', url: false)
end
it 'should default to full url if value is a url' do
url = @session.current_url
expect(url).to match(/with_js$/)
expect(@session).to have_current_path(url)
expect(@session).not_to have_current_path('http://www.not_example.com/with_js')
end
it 'should ignore the query' do
@session.visit('/with_js?test=test')
expect(@session).to have_current_path('/with_js?test=test')
expect(@session).to have_current_path('/with_js', ignore_query: true)
uri = Addressable::URI.parse(@session.current_url)
uri.query = nil
expect(@session).to have_current_path(uri.to_s, ignore_query: true)
end
it 'should not raise an exception if the current_url is nil' do
allow(@session).to receive(:current_url).and_return(nil)
allow(@session.page).to receive(:current_url).and_return(nil) if @session.respond_to? :page
# Without ignore_query option
expect do
expect(@session).to have_current_path(nil)
end.not_to raise_exception
# With ignore_query option
expect do
expect(@session).to have_current_path(nil, ignore_query: true)
end.not_to raise_exception
end
it 'should accept a filter block that receives Addressable::URL' do
@session.visit('/with_js?a=3&b=defgh')
expect(@session).to have_current_path('/with_js', ignore_query: true) { |url|
url.query_values.keys == %w[a b]
}
end
end
Capybara::SpecHelper.spec '#has_no_current_path?' do
before do
@session.visit('/with_js')
end
it 'should be false if the page has the given current_path' do
expect(@session).not_to have_no_current_path('/with_js')
end
it 'should allow regexp matches' do
expect(@session).not_to have_no_current_path(/w[a-z]{3}_js/)
expect(@session).to have_no_current_path(/monkey/)
end
it 'should wait for current_path to disappear', requires: [:js] do
Capybara.using_wait_time(3) do
@session.click_link('Change page')
expect(@session).to have_no_current_path('/with_js')
end
end
it 'should be true if the page has not the given current_path' do
expect(@session).to have_no_current_path('/with_html')
end
it 'should not raise an exception if the current_url is nil' do
allow(@session).to receive(:current_url).and_return(nil)
allow(@session.page).to receive(:current_url).and_return(nil) if @session.respond_to? :page
# Without ignore_query option
expect do
expect(@session).not_to have_current_path('/with_js')
end.not_to raise_exception
# With ignore_query option
expect do
expect(@session).not_to have_current_path('/with_js', ignore_query: true)
end.not_to raise_exception
end
it 'should accept a filter block that receives Addressable::URL' do
expect(@session).to have_no_current_path('/with_js', ignore_query: true) { |url|
!url.query.nil?
}
end
end
| ruby | MIT | b3325b198464b806f07ec2011ceb532d6d5cf4ab | 2026-01-04T15:38:10.098638Z | false |
teamcapybara/capybara | https://github.com/teamcapybara/capybara/blob/b3325b198464b806f07ec2011ceb532d6d5cf4ab/lib/capybara/spec/session/assert_text_spec.rb | lib/capybara/spec/session/assert_text_spec.rb | # frozen_string_literal: true
Capybara::SpecHelper.spec '#assert_text' do
it 'should be true if the given text is on the page' do
@session.visit('/with_html')
expect(@session.assert_text('est')).to be(true)
expect(@session.assert_text('Lorem')).to be(true)
expect(@session.assert_text('Redirect')).to be(true)
expect(@session.assert_text(:Redirect)).to be(true)
expect(@session.assert_text('text with whitespace')).to be(true)
end
it 'should support collapsing whitespace' do
@session.visit('/with_html')
expect(@session.assert_text('text with whitespace', normalize_ws: true)).to be(true)
end
context 'with enabled default collapsing whitespace' do
before { Capybara.default_normalize_ws = true }
it 'should be true if the given unnormalized text is on the page' do
@session.visit('/with_html')
expect(@session.assert_text('text with whitespace', normalize_ws: false)).to be(true)
end
it 'should support collapsing whitespace' do
@session.visit('/with_html')
expect(@session.assert_text('text with whitespace')).to be(true)
end
end
it 'should take scopes into account' do
@session.visit('/with_html')
@session.within("//a[@title='awesome title']") do
expect(@session.assert_text('labore')).to be(true)
end
end
it 'should raise if scoped to an element which does not have the text' do
@session.visit('/with_html')
@session.within("//a[@title='awesome title']") do
expect do
@session.assert_text('monkey')
end.to raise_error(Capybara::ExpectationNotMet, 'expected to find text "monkey" in "labore"')
end
end
it 'should be true if :all given and text is invisible.' do
@session.visit('/with_html')
expect(@session.assert_text(:all, 'Some of this text is hidden!')).to be(true)
end
it 'should be true if `Capybara.ignore_hidden_elements = true` and text is invisible.' do
Capybara.ignore_hidden_elements = false
@session.visit('/with_html')
expect(@session.assert_text('Some of this text is hidden!')).to be(true)
end
it 'should raise error with a helpful message if the requested text is present but invisible' do
@session.visit('/with_html')
el = @session.find(:css, '#hidden-text')
expect do
el.assert_text(:visible, 'Some of this text is hidden!')
end.to raise_error(Capybara::ExpectationNotMet, /it was found 1 time including non-visible text/)
end
it 'should raise error with a helpful message if the requested text is present but with incorrect case' do
@session.visit('/with_html')
expect do
@session.assert_text('Text With Whitespace')
end.to raise_error(Capybara::ExpectationNotMet, /it was found 1 time using a case insensitive search/)
end
it 'should raise error with helpful message if requested text is present but invisible and with incorrect case', requires: [:js] do
@session.visit('/with_html')
el = @session.find(:css, '#uppercase')
expect do
el.assert_text('text here')
end.to raise_error(Capybara::ExpectationNotMet, /it was found 1 time using a case insensitive search and it was found 1 time including non-visible text/)
end
it 'should raise the correct error if requested text is missing but contains regex special characters' do
@session.visit('/with_html')
expect do
@session.assert_text('[]*.')
end.to raise_error(Capybara::ExpectationNotMet, /expected to find text "\[\]\*\."/)
end
it 'should be true if the text in the page matches given regexp' do
@session.visit('/with_html')
expect(@session.assert_text(/Lorem/)).to be(true)
end
it "should raise error if the text in the page doesn't match given regexp" do
@session.visit('/with_html')
expect do
@session.assert_text(/xxxxyzzz/)
end.to raise_error(Capybara::ExpectationNotMet, %r{\Aexpected to find text matching /xxxxyzzz/ in "This is a test\\nHeader Class(.+)"\Z})
end
it 'should escape any characters that would have special meaning in a regexp' do
@session.visit('/with_html')
expect do
@session.assert_text('.orem')
end.to raise_error(Capybara::ExpectationNotMet)
end
it 'should wait for text to appear', requires: [:js] do
Capybara.default_max_wait_time = 2
@session.visit('/with_js')
@session.click_link('Click me')
expect(@session.assert_text('Has been clicked')).to be(true)
end
context 'with between' do
it 'should be true if the text occurs within the range given' do
@session.visit('/with_count')
expect(@session.assert_text('count', between: 1..3)).to be(true)
end
it 'should be false if the text occurs more or fewer times than range' do
@session.visit('/with_html')
expect do
@session.find(:css, '.number').assert_text(/\d/, between: 0..1)
end.to raise_error(Capybara::ExpectationNotMet, 'expected to find text matching /\\d/ between 0 and 1 times but found 2 times in "42"')
end
end
context 'with wait', requires: [:js] do
it 'should find element if it appears before given wait duration' do
Capybara.using_wait_time(0) do
@session.visit('/with_js')
@session.find(:css, '#reload-list').click
@session.find(:css, '#the-list').assert_text("Foo\nBar", wait: 0.9)
end
end
it 'should raise error if it appears after given wait duration' do
Capybara.using_wait_time(0) do
@session.visit('/with_js')
@session.find(:css, '#reload-list').click
el = @session.find(:css, '#the-list', visible: false)
expect do
el.assert_text(:all, 'Foo Bar', wait: 0.3)
end.to raise_error(Capybara::ExpectationNotMet)
end
end
end
context 'with multiple count filters' do
before do
@session.visit('/with_html')
end
it 'ignores other filters when :count is specified' do
o = { count: 5,
minimum: 6,
maximum: 0,
between: 0..4 }
expect { @session.assert_text('Header', **o) }.not_to raise_error
end
context 'with no :count expectation' do
it 'fails if :minimum is not met' do
o = { minimum: 6,
maximum: 5,
between: 2..7 }
expect { @session.assert_text('Header', **o) }.to raise_error(Capybara::ExpectationNotMet)
end
it 'fails if :maximum is not met' do
o = { minimum: 0,
maximum: 0,
between: 2..7 }
expect { @session.assert_text('Header', **o) }.to raise_error(Capybara::ExpectationNotMet)
end
it 'fails if :between is not met' do
o = { minimum: 0,
maximum: 5,
between: 0..4 }
expect { @session.assert_text('Header', **o) }.to raise_error(Capybara::ExpectationNotMet)
end
it 'succeeds if all combineable expectations are met' do
o = { minimum: 0,
maximum: 5,
between: 2..7 }
expect { @session.assert_text('Header', **o) }.not_to raise_error
end
end
end
end
Capybara::SpecHelper.spec '#assert_no_text' do
it 'should raise error if the given text is on the page at least once' do
@session.visit('/with_html')
expect do
@session.assert_no_text('Lorem')
end.to raise_error(Capybara::ExpectationNotMet, /\Aexpected not to find text "Lorem" in "This is a test.*"\z/)
end
it 'should be true if scoped to an element which does not have the text' do
@session.visit('/with_html')
@session.within("//a[@title='awesome title']") do
expect(@session.assert_no_text('monkey')).to be(true)
end
end
it 'should be true if the given text is on the page but not visible' do
@session.visit('/with_html')
expect(@session.assert_no_text('Inside element with hidden ancestor')).to be(true)
end
it 'should raise error if :all given and text is invisible.' do
@session.visit('/with_html')
el = @session.find(:css, '#hidden-text', visible: false)
expect do
el.assert_no_text(:all, 'Some of this text is hidden!')
end.to raise_error(Capybara::ExpectationNotMet, 'expected not to find text "Some of this text is hidden!" in "Some of this text is hidden!"')
end
it 'should raise error if :all given and text is invisible.' do
@session.visit('/with_html')
el = @session.find(:css, '#some-hidden-text', visible: false)
expect do
el.assert_no_text(:visible, 'hidden')
end.to raise_error(Capybara::ExpectationNotMet, 'expected not to find text "hidden" in "Some of this text is not hidden"')
end
it "should be true if the text in the page doesn't match given regexp" do
@session.visit('/with_html')
@session.assert_no_text(/xxxxyzzz/)
end
context 'with count' do
it 'should be true if the text occurs within the range given' do
@session.visit('/with_count')
expect(@session.assert_text('count', count: 2)).to be(true)
end
it 'should be false if the text occurs more or fewer times than range' do
@session.visit('/with_html')
expect do
@session.find(:css, '.number').assert_text(/\d/, count: 1)
end.to raise_error(Capybara::ExpectationNotMet, 'expected to find text matching /\\d/ 1 time but found 2 times in "42"')
end
end
context 'with wait', requires: [:js] do
it 'should not find element if it appears after given wait duration' do
@session.visit('/with_js')
@session.click_link('Click me')
@session.find(:css, '#reload-list').click
@session.find(:css, '#the-list').assert_no_text('Foo Bar', wait: 0.3)
end
end
end
| ruby | MIT | b3325b198464b806f07ec2011ceb532d6d5cf4ab | 2026-01-04T15:38:10.098638Z | false |
teamcapybara/capybara | https://github.com/teamcapybara/capybara/blob/b3325b198464b806f07ec2011ceb532d6d5cf4ab/lib/capybara/spec/session/has_table_spec.rb | lib/capybara/spec/session/has_table_spec.rb | # frozen_string_literal: true
Capybara::SpecHelper.spec '#has_table?' do
before do
@session.visit('/tables')
end
it 'should be true if the table is on the page' do
expect(@session).to have_table('Villain')
expect(@session).to have_table('villain_table')
expect(@session).to have_table(:villain_table)
end
it 'should accept rows with column header hashes' do
expect(@session).to have_table('Horizontal Headers', with_rows:
[
{ 'First Name' => 'Vern', 'Last Name' => 'Konopelski', 'City' => 'Everette' },
{ 'First Name' => 'Palmer', 'Last Name' => 'Sawayn', 'City' => 'West Trinidad' }
])
end
it 'should accept rows with partial column header hashes' do
expect(@session).to have_table('Horizontal Headers', with_rows:
[
{ 'First Name' => 'Thomas' },
{ 'Last Name' => 'Sawayn', 'City' => 'West Trinidad' }
])
expect(@session).not_to have_table('Horizontal Headers', with_rows:
[
{ 'Unmatched Header' => 'Thomas' }
])
end
it 'should accept rows with array of cell values' do
expect(@session).to have_table('Horizontal Headers', with_rows:
[
%w[Thomas Walpole Oceanside],
['Ratke', 'Lawrence', 'East Sorayashire']
])
end
it 'should consider order of cells in each row' do
expect(@session).not_to have_table('Horizontal Headers', with_rows:
[
%w[Thomas Walpole Oceanside],
['Lawrence', 'Ratke', 'East Sorayashire']
])
end
it 'should accept all rows with array of cell values' do
expect(@session).to have_table('Horizontal Headers', rows:
[
%w[Thomas Walpole Oceanside],
%w[Danilo Wilkinson Johnsonville],
%w[Vern Konopelski Everette],
['Ratke', 'Lawrence', 'East Sorayashire'],
['Palmer', 'Sawayn', 'West Trinidad']
])
end
it 'should match with vertical headers' do
expect(@session).to have_table('Vertical Headers', with_cols:
[
{ 'First Name' => 'Thomas' },
{ 'First Name' => 'Danilo', 'Last Name' => 'Wilkinson', 'City' => 'Johnsonville' },
{ 'Last Name' => 'Sawayn', 'City' => 'West Trinidad' }
])
end
it 'should match col with array of cell values' do
expect(@session).to have_table('Vertical Headers', with_cols:
[
%w[Vern Konopelski Everette]
])
end
it 'should match cols with array of cell values' do
expect(@session).to have_table('Vertical Headers', with_cols:
[
%w[Danilo Wilkinson Johnsonville],
%w[Vern Konopelski Everette]
])
end
it 'should match all cols with array of cell values' do
expect(@session).to have_table('Vertical Headers', cols:
[
%w[Thomas Walpole Oceanside],
%w[Danilo Wilkinson Johnsonville],
%w[Vern Konopelski Everette],
['Ratke', 'Lawrence', 'East Sorayashire'],
['Palmer', 'Sawayn', 'West Trinidad']
])
end
it "should not match if the order of cell values doesn't match" do
expect(@session).not_to have_table('Vertical Headers', with_cols:
[
%w[Vern Everette Konopelski]
])
end
it "should not match with vertical headers if the columns don't match" do
expect(@session).not_to have_table('Vertical Headers', with_cols:
[
{ 'First Name' => 'Thomas' },
{ 'First Name' => 'Danilo', 'Last Name' => 'Walpole', 'City' => 'Johnsonville' },
{ 'Last Name' => 'Sawayn', 'City' => 'West Trinidad' }
])
expect(@session).not_to have_table('Vertical Headers', with_cols:
[
{ 'Unmatched Header' => 'Thomas' }
])
end
it 'should be false if the table is not on the page' do
expect(@session).not_to have_table('Monkey')
end
it 'should find row by header and cell values' do
expect(@session.find(:table, 'Horizontal Headers')).to have_selector(:table_row, 'First Name' => 'Thomas', 'Last Name' => 'Walpole')
expect(@session.find(:table, 'Horizontal Headers')).to have_selector(:table_row, 'Last Name' => 'Walpole')
expect(@session.find(:table, 'Horizontal Headers')).not_to have_selector(:table_row, 'First Name' => 'Walpole')
expect(@session.find(:table, 'Horizontal Headers')).not_to have_selector(:table_row, 'Unmatched Header' => 'Thomas')
end
it 'should find row by cell values' do
expect(@session.find(:table, 'Horizontal Headers')).to have_selector(:table_row, %w[Thomas Walpole Oceanside])
expect(@session.find(:table, 'Horizontal Headers')).not_to have_selector(:table_row, %w[Walpole Thomas])
expect(@session.find(:table, 'Horizontal Headers')).not_to have_selector(:table_row, %w[Other])
end
it 'should find row by all rows without locator values' do
table = @session.find(:table, 'Horizontal Headers')
expect(table).to have_selector(:table_row)
expect(table).to have_selector(:table_row, count: 6)
end
end
Capybara::SpecHelper.spec '#has_no_table?' do
before do
@session.visit('/tables')
end
it 'should be false if the table is on the page' do
expect(@session).not_to have_no_table('Villain')
expect(@session).not_to have_no_table('villain_table')
end
it 'should be true if the table is not on the page' do
expect(@session).to have_no_table('Monkey')
end
it 'should consider rows' do
expect(@session).to have_no_table('Horizontal Headers', with_rows:
[
{ 'First Name' => 'Thomas', 'City' => 'Los Angeles' }
])
end
context 'using :with_cols' do
it 'should consider a single column' do
expect(@session).to have_no_table('Vertical Headers', with_cols:
[
{ 'First Name' => 'Joe' }
])
end
it 'should be true even if the last column does exist' do
expect(@session).to have_no_table('Vertical Headers', with_cols:
[
{
'First Name' => 'What?',
'What?' => 'Walpole',
'City' => 'Oceanside' # This line makes the example fail
}
])
end
it 'should be true if none of the columns exist' do
expect(@session).to have_no_table('Vertical Headers', with_cols:
[
{
'First Name' => 'What?',
'What?' => 'Walpole',
'City' => 'What?'
}
])
end
it 'should be true if the first column does match' do
expect(@session).to have_no_table('Vertical Headers', with_cols:
[
{
'First Name' => 'Thomas',
'Last Name' => 'What',
'City' => 'What'
}
])
end
it 'should be true if none of the columns match' do
expect(@session).to have_no_table('Vertical Headers', with_cols:
[
{
'First Name' => 'What',
'Last Name' => 'What',
'City' => 'What'
}
])
end
end
end
| ruby | MIT | b3325b198464b806f07ec2011ceb532d6d5cf4ab | 2026-01-04T15:38:10.098638Z | false |
teamcapybara/capybara | https://github.com/teamcapybara/capybara/blob/b3325b198464b806f07ec2011ceb532d6d5cf4ab/lib/capybara/spec/session/window/current_window_spec.rb | lib/capybara/spec/session/window/current_window_spec.rb | # frozen_string_literal: true
Capybara::SpecHelper.spec '#current_window', requires: [:windows] do
before do
@window = @session.current_window
@session.visit('/with_windows')
end
after do
(@session.windows - [@window]).each do |w|
@session.switch_to_window w
w.close
end
@session.switch_to_window(@window)
end
it 'should return window' do
expect(@session.current_window).to be_instance_of(Capybara::Window)
end
it 'should be modified by switching to another window' do
window = @session.window_opened_by { @session.find(:css, '#openWindow').click }
expect do
@session.switch_to_window(window)
end.to change { @session.current_window }.from(@window).to(window)
end
end
| ruby | MIT | b3325b198464b806f07ec2011ceb532d6d5cf4ab | 2026-01-04T15:38:10.098638Z | false |
teamcapybara/capybara | https://github.com/teamcapybara/capybara/blob/b3325b198464b806f07ec2011ceb532d6d5cf4ab/lib/capybara/spec/session/window/become_closed_spec.rb | lib/capybara/spec/session/window/become_closed_spec.rb | # frozen_string_literal: true
Capybara::SpecHelper.spec '#become_closed', requires: %i[windows js] do
let!(:window) { @session.current_window }
let(:other_window) do
@session.window_opened_by do
@session.find(:css, '#openWindow').click
end
end
before do
@session.visit('/with_windows')
end
after do
@session.document.synchronize(5, errors: [Capybara::CapybaraError]) do
raise Capybara::CapybaraError if @session.windows.size != 1
end
@session.switch_to_window(window)
end
context 'with :wait option' do
it 'should wait if value of :wait is more than timeout' do
@session.within_window other_window do
@session.execute_script('setTimeout(function(){ window.close(); }, 500);')
end
Capybara.using_wait_time 0.1 do
expect(other_window).to become_closed(wait: 5)
end
end
it 'should raise error if value of :wait is less than timeout' do
@session.within_window other_window do
@session.execute_script('setTimeout(function(){ window.close(); }, 1000);')
end
Capybara.using_wait_time 2 do
expect do
expect(other_window).to become_closed(wait: 0.2)
end.to raise_error(RSpec::Expectations::ExpectationNotMetError, /\Aexpected #<Window @handle=".+"> to become closed after 0.2 seconds\Z/)
end
end
end
context 'without :wait option' do
it 'should wait if value of default_max_wait_time is more than timeout' do
@session.within_window other_window do
@session.execute_script('setTimeout(function(){ window.close(); }, 500);')
end
Capybara.using_wait_time 5 do
expect(other_window).to become_closed
end
end
it 'should raise error if value of default_max_wait_time is less than timeout' do
@session.within_window other_window do
@session.execute_script('setTimeout(function(){ window.close(); }, 900);')
end
Capybara.using_wait_time 0.4 do
expect do
expect(other_window).to become_closed
end.to raise_error(RSpec::Expectations::ExpectationNotMetError, /\Aexpected #<Window @handle=".+"> to become closed after 0.4 seconds\Z/)
end
end
end
context 'with not_to' do
it "should not raise error if window doesn't close before default_max_wait_time" do
@session.within_window other_window do
@session.execute_script('setTimeout(function(){ window.close(); }, 1000);')
end
Capybara.using_wait_time 0.3 do
expect do
expect(other_window).not_to become_closed
end.not_to raise_error
end
end
it 'should raise error if window closes before default_max_wait_time' do
@session.within_window other_window do
@session.execute_script('setTimeout(function(){ window.close(); }, 700);')
end
Capybara.using_wait_time 3.1 do
expect do
expect(other_window).not_to become_closed
end.to raise_error(RSpec::Expectations::ExpectationNotMetError, /\Aexpected #<Window @handle=".+"> not to become closed after 3.1 seconds\Z/)
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/spec/session/window/window_opened_by_spec.rb | lib/capybara/spec/session/window/window_opened_by_spec.rb | # frozen_string_literal: true
# NOTE: This file uses `sleep` to sync up parts of the tests. This is only implemented like this
# because of the methods being tested. In tests using Capybara this type of behavior should be implemented
# using Capybara provided assertions with builtin waiting behavior.
Capybara::SpecHelper.spec '#window_opened_by', requires: [:windows] do
before do
@window = @session.current_window
@session.visit('/with_windows')
@session.assert_selector(:css, 'body.loaded')
end
after do
(@session.windows - [@window]).each do |w|
@session.switch_to_window w
w.close
end
@session.switch_to_window(@window)
end
let(:zero_windows_message) { 'block passed to #window_opened_by opened 0 windows instead of 1' }
let(:two_windows_message) { 'block passed to #window_opened_by opened 2 windows instead of 1' }
context 'with :wait option' do
it 'should raise error if value of :wait is less than timeout' do
# So large value is used as `driver.window_handles` takes up to 800 ms on Travis
Capybara.using_wait_time 2 do
button = @session.find(:css, '#openWindowWithLongerTimeout')
expect do
@session.window_opened_by(wait: 0.3) do
button.click
end
end.to raise_error(Capybara::WindowError, zero_windows_message)
end
@session.document.synchronize(5, errors: [Capybara::CapybaraError]) do
raise Capybara::CapybaraError if @session.windows.size != 2
end
end
it 'should find window if value of :wait is more than timeout' do
button = @session.find(:css, '#openWindowWithTimeout')
Capybara.using_wait_time 0.1 do
window = @session.window_opened_by(wait: 1.5) do
button.click
end
expect(window).to be_instance_of(Capybara::Window)
end
end
end
context 'without :wait option' do
it 'should raise error if default_max_wait_time is less than timeout' do
button = @session.find(:css, '#openWindowWithTimeout')
Capybara.using_wait_time 0.1 do
expect do
@session.window_opened_by do
button.click
end
end.to raise_error(Capybara::WindowError, zero_windows_message)
end
@session.document.synchronize(2, errors: [Capybara::CapybaraError]) do
raise Capybara::CapybaraError if @session.windows.size != 2
end
end
it 'should find window if default_max_wait_time is more than timeout' do
button = @session.find(:css, '#openWindowWithTimeout')
Capybara.using_wait_time 5 do
window = @session.window_opened_by do
button.click
end
expect(window).to be_instance_of(Capybara::Window)
end
end
end
it 'should raise error when two windows have been opened by block' do
button = @session.find(:css, '#openTwoWindows')
expect do
@session.window_opened_by do
button.click
sleep 1 # It's possible for window_opened_by to be fullfilled before the second window opens
end
end.to raise_error(Capybara::WindowError, two_windows_message)
@session.document.synchronize(2, errors: [Capybara::CapybaraError]) do
raise Capybara::CapybaraError if @session.windows.size != 3
end
end
it 'should raise error when no windows were opened by block' do
button = @session.find(:css, '#doesNotOpenWindows')
expect do
@session.window_opened_by do
button.click
end
end.to raise_error(Capybara::WindowError, zero_windows_message)
end
end
| ruby | MIT | b3325b198464b806f07ec2011ceb532d6d5cf4ab | 2026-01-04T15:38:10.098638Z | false |
teamcapybara/capybara | https://github.com/teamcapybara/capybara/blob/b3325b198464b806f07ec2011ceb532d6d5cf4ab/lib/capybara/spec/session/window/windows_spec.rb | lib/capybara/spec/session/window/windows_spec.rb | # frozen_string_literal: true
# NOTE: This file uses `sleep` to sync up parts of the tests. This is only implemented like this
# because of the methods being tested. In tests using Capybara this type of behavior should be implemented
# using Capybara provided assertions with builtin waiting behavior.
Capybara::SpecHelper.spec '#windows', requires: [:windows] do
before do
@window = @session.current_window
@session.visit('/with_windows')
@session.find(:css, '#openTwoWindows').click
@session.document.synchronize(3, errors: [Capybara::CapybaraError]) do
raise Capybara::CapybaraError if @session.windows.size != 3
end
end
after do
(@session.windows - [@window]).each(&:close)
@session.switch_to_window(@window)
end
it 'should return objects of Capybara::Window class' do
expect(@session.windows.map { |window| window.instance_of?(Capybara::Window) }).to eq([true] * 3)
end
it 'should be able to switch to windows' do
sleep 1 # give windows enough time to fully load
titles = @session.windows.map do |window|
@session.within_window(window) { @session.title }
end
expect(titles).to match_array(['With Windows', 'Title of the first popup', 'Title of popup two']) # rubocop:disable RSpec/MatchArray
end
end
| ruby | MIT | b3325b198464b806f07ec2011ceb532d6d5cf4ab | 2026-01-04T15:38:10.098638Z | false |
teamcapybara/capybara | https://github.com/teamcapybara/capybara/blob/b3325b198464b806f07ec2011ceb532d6d5cf4ab/lib/capybara/spec/session/window/within_window_spec.rb | lib/capybara/spec/session/window/within_window_spec.rb | # frozen_string_literal: true
Capybara::SpecHelper.spec '#within_window', requires: [:windows] do
before do
@window = @session.current_window
@session.visit('/with_windows')
@session.find(:css, '#openTwoWindows').click
@session.document.synchronize(3, errors: [Capybara::CapybaraError]) do
raise Capybara::CapybaraError if @session.windows.size != 3
end
end
after do
(@session.windows - [@window]).each do |w|
@session.switch_to_window w
w.close
end
@session.switch_to_window(@window)
end
context 'with an instance of Capybara::Window' do
it 'should not invoke driver#switch_to_window when given current window' do
allow(@session.driver).to receive(:switch_to_window).and_call_original
@session.within_window @window do
expect(@session.title).to eq('With Windows')
end
expect(@session.driver).not_to have_received(:switch_to_window)
end
it 'should be able to switch to another window' do
window = (@session.windows - [@window]).first
@session.within_window window do
expect(@session).to have_title(/Title of the first popup|Title of popup two/)
end
expect(@session.title).to eq('With Windows')
end
it 'returns value from the block' do
window = (@session.windows - [@window]).first
value = @session.within_window window do
43252003274489856000
end
expect(value).to eq(43252003274489856000)
end
it 'should switch back if exception was raised inside block' do
window = (@session.windows - [@window]).first
expect do
@session.within_window(window) do
@session.within 'html' do
raise 'some error'
end
end
end.to raise_error(StandardError, 'some error')
expect(@session.current_window).to eq(@window)
expect(@session).to have_css('#doesNotOpenWindows')
expect(@session.send(:scopes)).to eq([nil])
end
it 'should leave correct scopes after execution in case of error', requires: %i[windows frames] do
window = (@session.windows - [@window]).first
expect do
@session.within_frame 'frameOne' do
@session.within_window(window) {}
end
end.to raise_error(Capybara::ScopeError)
expect(@session.current_window).to eq(@window)
expect(@session).to have_css('#doesNotOpenWindows')
expect(@session.send(:scopes)).to eq([nil])
end
it 'should raise error if closed window was passed' do
other_window = (@session.windows - [@window]).first
@session.within_window other_window do
other_window.close
end
expect do
@session.within_window(other_window) do
raise 'should not be invoked'
end
end.to raise_error(@session.driver.no_such_window_error)
expect(@session.current_window).to eq(@window)
expect(@session).to have_css('#doesNotOpenWindows')
expect(@session.send(:scopes)).to eq([nil])
end
end
context 'with lambda' do
it 'should find the div in another window' do
@session.within_window(-> { @session.title == 'Title of the first popup' }) do
expect(@session).to have_css('#divInPopupOne')
end
end
it 'should find divs in both windows' do
@session.within_window(-> { @session.title == 'Title of popup two' }) do
expect(@session).to have_css('#divInPopupTwo')
end
@session.within_window(-> { @session.title == 'Title of the first popup' }) do
expect(@session).to have_css('#divInPopupOne')
end
expect(@session.title).to eq('With Windows')
end
it 'should be able to nest within_window' do
@session.within_window(-> { @session.title == 'Title of popup two' }) do
expect(@session).to have_css('#divInPopupTwo')
@session.within_window(-> { @session.title == 'Title of the first popup' }) do
expect(@session).to have_css('#divInPopupOne')
end
expect(@session).to have_css('#divInPopupTwo')
expect(@session).not_to have_css('divInPopupOne')
end
expect(@session).not_to have_css('#divInPopupTwo')
expect(@session).not_to have_css('divInPopupOne')
expect(@session.title).to eq('With Windows')
end
it 'should work inside a normal scope' do
expect(@session).to have_css('#openWindow')
@session.within(:css, '#scope') do
@session.within_window(-> { @session.title == 'Title of the first popup' }) do
expect(@session).to have_css('#divInPopupOne')
end
expect(@session).to have_content('My scoped content')
expect(@session).not_to have_css('#openWindow')
end
end
it "should raise error if window wasn't found" do
expect do
@session.within_window(-> { @session.title == 'Invalid title' }) do
expect(@session).to have_css('#divInPopupOne')
end
end.to raise_error(Capybara::WindowError, 'Could not find a window matching block/lambda')
expect(@session.current_window).to eq(@window)
expect(@session).to have_css('#doesNotOpenWindows')
expect(@session.send(:scopes)).to eq([nil])
end
it 'returns value from the block' do
value = @session.within_window(-> { @session.title == 'Title of popup two' }) { 42 }
expect(value).to eq(42)
end
it 'should switch back if exception was raised inside block' do
expect do
@session.within_window(-> { @session.title == 'Title of popup two' }) do
raise 'some error'
end
end.to raise_error(StandardError, 'some error')
expect(@session.current_window).to eq(@window)
expect(@session.send(:scopes)).to eq([nil])
end
end
end
| ruby | MIT | b3325b198464b806f07ec2011ceb532d6d5cf4ab | 2026-01-04T15:38:10.098638Z | false |
teamcapybara/capybara | https://github.com/teamcapybara/capybara/blob/b3325b198464b806f07ec2011ceb532d6d5cf4ab/lib/capybara/spec/session/window/switch_to_window_spec.rb | lib/capybara/spec/session/window/switch_to_window_spec.rb | # frozen_string_literal: true
# NOTE: This file uses `sleep` to sync up parts of the tests. This is only implemented like this
# because of the methods being tested. In tests using Capybara this type of behavior should be implemented
# using Capybara provided assertions with builtin waiting behavior.
Capybara::SpecHelper.spec '#switch_to_window', requires: [:windows] do
before do
@window = @session.current_window
@session.visit('/with_windows')
@session.assert_selector(:css, 'body.loaded')
end
after do
(@session.windows - [@window]).each do |w|
@session.switch_to_window w
w.close
end
@session.switch_to_window(@window)
end
it 'should raise error when invoked without args' do
expect do
@session.switch_to_window
end.to raise_error(ArgumentError, '`switch_to_window`: either window or block should be provided')
end
it 'should raise error when invoked with window and block' do
expect do
@session.switch_to_window(@window) { @session.title == 'Title of the first popup' }
end.to raise_error(ArgumentError, '`switch_to_window` can take either a block or a window, not both')
end
context 'with an instance of Capybara::Window' do
it 'should be able to switch to window' do
window = @session.open_new_window
expect(@session.title).to eq('With Windows')
@session.switch_to_window(window)
expect(@session.title).to satisfy('be a blank title') { |title| ['', 'about:blank'].include? title }
end
it 'should raise error when closed window is passed' do
original_window = @session.current_window
new_window = @session.open_new_window
@session.switch_to_window(new_window)
new_window.close
@session.switch_to_window(original_window)
expect do
@session.switch_to_window(new_window)
end.to raise_error(@session.driver.no_such_window_error)
end
end
context 'with block' do
before do
@session.find(:css, '#openTwoWindows').click
sleep(1) # wait for the windows to open
end
it 'should be able to switch to current window' do
@session.switch_to_window { @session.title == 'With Windows' }
expect(@session).to have_css('#openTwoWindows')
end
it 'should find the div in another window' do
@session.switch_to_window { @session.title == 'Title of popup two' }
expect(@session).to have_css('#divInPopupTwo')
end
it 'should be able to switch multiple times' do
@session.switch_to_window { @session.title == 'Title of the first popup' }
expect(@session).to have_css('#divInPopupOne')
@session.switch_to_window { @session.title == 'Title of popup two' }
expect(@session).to have_css('#divInPopupTwo')
end
it 'should return window' do
window = @session.switch_to_window { @session.title == 'Title of popup two' }
expect(@session.windows - [@window]).to include(window)
end
it "should raise error when invoked inside `within` as it's nonsense" do
expect do
@session.within(:css, '#doesNotOpenWindows') do
@session.switch_to_window { @session.title == 'With Windows' }
end
end.to raise_error(Capybara::ScopeError, /`switch_to_window` is not supposed to be invoked/)
end
it "should raise error when invoked inside `within_frame` as it's nonsense" do
expect do
@session.within_frame('frameOne') do
@session.switch_to_window { @session.title == 'With Windows' }
end
end.to raise_error(Capybara::ScopeError, /`switch_to_window` is not supposed to be invoked from/)
end
it 'should allow to be called inside within_window and within_window will still return to original' do
other_windows = (@session.windows - [@window])
expect(@session.current_window).to eq(@window)
@session.within_window other_windows[0] do
expect(@session.current_window).to eq(other_windows[0])
@session.switch_to_window other_windows[1]
expect(@session.current_window).to eq(other_windows[1])
end
expect(@session.current_window).to eq(@window)
end
it "should raise error if window matching block wasn't found" do
original = @session.current_window
expect do
@session.switch_to_window { @session.title == 'A title' }
end.to raise_error(Capybara::WindowError, 'Could not find a window matching block/lambda')
expect(@session.current_window).to eq(original)
end
it 'should switch to original window if error is raised inside block' do
original = @session.switch_to_window(@session.windows[1])
expect do
@session.switch_to_window { raise 'error' }
end.to raise_error(StandardError, 'error')
expect(@session.current_window).to eq(original)
end
end
it 'should wait for window to appear' do
@session.find(:css, '#openWindowWithTimeout').click
expect do
@session.switch_to_window(wait: 5) { @session.title == 'Title of the first popup' }
end.not_to raise_error
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.