Module: RSpec::Matchers
Overview
Matchers
provides a number of useful matchers we use to define expectations. Any object that implements the [matcher protocol](Matchers/MatcherProtocol) can be used as a matcher.
Predicates
In addition to matchers that are defined explicitly, ::RSpec
will create custom matchers on the fly for any arbitrary predicate, giving your specs a much more natural language feel.
A Ruby predicate is a method that ends with a “?” and returns true or false. Common examples are empty?
, nil?
, and instance_of?
.
All you need to do is write ‘expect(..).to be_` followed by the predicate without the question mark, and ::RSpec
will figure it out from there. For example:
expect([]).to be_empty # => [].empty?() | passes
expect([]).not_to be_empty # => [].empty?() | fails
In addition to prefixing the predicate matchers with “be_”, you can also use “be_a_” and “be_an_”, making your specs read much more naturally:
expect("a string").to be_an_instance_of(String) # =>"a string".instance_of?(String) # passes
expect(3).to be_a_kind_of(Integer) # => 3.kind_of?(Numeric) | passes
expect(3).to be_a_kind_of(Numeric) # => 3.kind_of?(Numeric) | passes
expect(3).to be_an_instance_of(Integer) # => 3.instance_of?(Integer) | passes
expect(3).not_to be_an_instance_of(Numeric) # => 3.instance_of?(Numeric) | fails
::RSpec
will also create custom matchers for predicates like has_key?
. To use this feature, just state that the object should have_key(:key) and ::RSpec
will call has_key?(:key) on the target. For example:
expect(:a => "A").to have_key(:a)
expect(:a => "A").to have_key(:b) # fails
You can use this feature to invoke any predicate that begins with “has_”, whether it is part of the Ruby libraries (like Hash#has_key?
) or a method you wrote on your own class.
Note that ::RSpec
does not provide composable aliases for these dynamic predicate matchers. You can easily define your own aliases, though:
RSpec::Matchers.alias_matcher :a_user_who_is_an_admin, :be_an_admin
expect(user_list).to include(a_user_who_is_an_admin)
Alias Matchers
With .alias_matcher, you can easily create an alternate name for a given matcher.
The description will also change according to the new name:
RSpec::Matchers.alias_matcher :a_list_that_sums_to, :sum_to
sum_to(3).description # => "sum to 3"
a_list_that_sums_to(3).description # => "a list that sums to 3"
or you can specify a custom description like this:
RSpec::Matchers.alias_matcher :a_list_sorted_by, :be_sorted_by do |description|
description.sub("be sorted by", "a list sorted by")
end
be_sorted_by(:age).description # => "be sorted by age"
a_list_sorted_by(:age).description # => "a list sorted by age"
Custom Matchers
When you find that none of the stock matchers provide a natural feeling expectation, you can very easily write your own using RSpec’s matcher DSL
or writing one from scratch.
Matcher DSL
Imagine that you are writing a game in which players can be in various zones on a virtual board. To specify that bob should be in zone 4, you could say:
expect(bob.current_zone).to eql(Zone.new("4"))
But you might find it more expressive to say:
expect(bob).to be_in_zone("4")
and/or
expect(bob).not_to be_in_zone("3")
You can create such a matcher like so:
RSpec::Matchers.define :be_in_zone do |zone|
match do |player|
player.in_zone?(zone)
end
end
This will generate a be_in_zone
method that returns a matcher with logical default messages for failures. You can override the failure messages and the generated description as follows:
RSpec::Matchers.define :be_in_zone do |zone|
match do |player|
player.in_zone?(zone)
end
do |player|
# generate and return the appropriate string.
end
do |player|
# generate and return the appropriate string.
end
description do
# generate and return the appropriate string.
end
end
Each of the message-generation methods has access to the block arguments passed to the create
method (in this case, zone
). The failure message methods (failure_message
and failure_message_when_negated
) are passed the actual value (the receiver of expect(..)
or expect(..).not_to
).
Custom Matcher from scratch
You could also write a custom matcher from scratch, as follows:
class BeInZone
def initialize(expected)
@expected = expected
end
def matches?(target)
@target = target
@target.current_zone.eql?(Zone.new(@expected))
end
def
"expected #{@target.inspect} to be in Zone #{@expected}"
end
def
"expected #{@target.inspect} not to be in Zone #{@expected}"
end
end
… and a method like this:
def be_in_zone(expected)
BeInZone.new(expected)
end
And then expose the method to your specs. This is normally done by including the method and the class in a module, which is then included in your spec:
module CustomGameMatchers
class BeInZone
# ...
end
def be_in_zone(expected)
# ...
end
end
describe "Player behaviour" do
include CustomGameMatchers
# ...
end
or you can include in globally in a spec_helper.rb file require
d from your spec file(s):
RSpec::configure do |config|
config.include(CustomGameMatchers)
end
Making custom matchers composable
RSpec’s built-in matchers are designed to be composed, in expressions like:
expect(["barn", 2.45]).to contain_exactly(
a_value_within(0.1).of(2.5),
a_string_starting_with("bar")
)
Custom matchers can easily participate in composed matcher expressions like these. Include Composable
in your custom matcher to make it support being composed (matchers defined using the DSL
have this included automatically). Within your matcher’s matches?
method (or the #match block, if using the DSL
), use ‘values_match?(expected, actual)` rather than `expected == actual`. Under the covers, values_match?
is able to match arbitrary nested data structures containing a mix of both matchers and non-matcher objects. It uses ===
and ==
to perform the matching, considering the values to match if either returns true
. The Composable
mixin also provides some helper methods for surfacing the matcher descriptions within your matcher’s description or failure messages.
RSpec’s built-in matchers each have a number of aliases that rephrase the matcher from a verb phrase (such as #be_within) to a noun phrase (such as #a_value_within), which reads better when the matcher is passed as an argument in a composed matcher expressions, and also uses the noun-phrase wording in the matcher’s description
, for readable failure messages. You can alias your custom matchers in similar fashion using .alias_matcher.
Negated Matchers
Sometimes if you want to test for the opposite using a more descriptive name instead of using not_to
, you can use .define_negated_matcher:
RSpec::Matchers.define_negated_matcher :exclude, :include
include(1, 2).description # => "include 1 and 2"
exclude(1, 2).description # => "exclude 1 and 2"
While the most obvious negated form may be to add a not_
prefix, the failure messages you get with that form can be confusing (e.g. “expected [actual] to not [verb], but did not”). We’ve found it works best to find a more positive name for the negated form, such as avoid_changing
rather than not_change
.
Constant Summary
-
BE_PREDICATE_REGEX =
# File 'rspec-expectations/lib/rspec/matchers.rb', line 957/^(?:be_(?:an?_)?)(.*)/
-
DYNAMIC_MATCHER_REGEX =
# File 'rspec-expectations/lib/rspec/matchers.rb', line 959Regexp.union(BE_PREDICATE_REGEX, HAS_REGEX)
-
HAS_REGEX =
# File 'rspec-expectations/lib/rspec/matchers.rb', line 958/^(?:have_)(.*)/
Class Attribute Summary
- .last_expectation_handler rw Internal use only Internal use only
- .last_matcher rw Internal use only Internal use only
Class Method Summary
-
.alias_matcher(new_name, old_name, options = {}, &description_override)
Extended from DSL#alias_matcher.
-
.clear_generated_description
Internal use only
Internal use only
Used by rspec-core to clear the state used to generate descriptions after an example.
-
.configuration ⇒ RSpec::Expectations::Configuration
Delegates to Expectations.configuration.
-
.define(name, &declarations)
Extended from DSL#define.
-
.define_negated_matcher(negated_name, base_name, &description_override)
Extended from DSL#define_negated_matcher.
-
.generated_description
Internal use only
Internal use only
Generates an an example description based on the last expectation.
- .last_description Internal use only Internal use only
-
.append_features(mod)
private
Internal use only
Internal use only
Note that
included
doesn’t work for this because it is triggered afterMatchers
is an ancestor of the inclusion host, rather than before, like .append_features. - .is_a_describable_matcher?(obj) ⇒ Boolean private Internal use only Internal use only
- .is_a_matcher?(obj) ⇒ Boolean private Internal use only Internal use only
DSL
- Extended
alias_matcher | Defines a matcher alias. |
define | Defines a custom matcher. |
define_negated_matcher | Defines a negated matcher. |
matcher | Alias for DSL#define. |
warn_about_block_args | :nocov: |
Instance Method Summary
-
#a_block_changing(receiver = nil, message = nil, &block)
Alias for #change.
-
#a_block_outputting(expected = nil)
Alias for #output.
-
#a_block_raising(error = BuiltIn::RaiseError::UndefinedValue, message = nil, &block)
Alias for #raise_error.
-
#a_block_throwing(expected_symbol = nil, expected_arg = nil)
Alias for #throw_symbol.
-
#a_block_yielding_control
Alias for #yield_control.
-
#a_block_yielding_successive_args(*args)
Alias for #yield_successive_args.
-
#a_block_yielding_with_args(*args)
Alias for #yield_with_args.
-
#a_block_yielding_with_no_args
Alias for #yield_with_no_args.
-
#a_collection_containing_exactly(*items)
Alias for #contain_exactly.
-
#a_collection_ending_with(*expected)
Alias for #end_with.
-
#a_collection_including(*expected)
Alias for #include.
-
#a_collection_starting_with(*expected)
Alias for #start_with.
-
#a_falsey_value
Alias for #be_falsey.
-
#a_falsy_value
Alias for #be_falsey.
-
#a_hash_including(*expected)
Alias for #include.
-
#a_kind_of(expected)
Alias for #be_a_kind_of.
-
#a_nil_value
Alias for #be_nil.
-
#a_range_covering(*values)
Alias for #cover.
-
#a_string_ending_with(*expected)
Alias for #end_with.
-
#a_string_including(*expected)
Alias for #include.
-
#a_string_matching(expected)
Alias for #match.
-
#a_string_starting_with(*expected)
Alias for #start_with.
-
#a_truthy_value
Alias for #be_truthy.
-
#a_value(*args)
Alias for #be.
-
#a_value_between(min, max)
Alias for #be_between.
-
#a_value_within(delta)
Alias for #be_within.
-
#aggregate_failures(label = nil, metadata = {}) { ... }
Allows multiple expectations in the provided block to fail, and then aggregates them into a single exception, rather than aborting on the first expectation failure like normal.
-
#all(expected)
Passes if the provided matcher passes when checked against all elements of the collection.
-
#an_array_matching(items)
Alias for #match_array.
-
#an_instance_of(expected)
Alias for #be_an_instance_of.
-
#an_object_eq_to(expected)
Alias for #eq.
-
#an_object_eql_to(expected)
Alias for #eql.
-
#an_object_equal_to(expected)
Alias for #equal.
-
#an_object_existing(*args)
Alias for #exist.
-
#an_object_having_attributes(expected)
Alias for #have_attributes.
-
#an_object_matching(expected)
Alias for #match.
-
#an_object_responding_to(*names)
Alias for #respond_to.
-
#an_object_satisfying(description = nil, &block)
Alias for #satisfy.
-
#be(*args)
(also: #a_value)
Given true, false, or nil, will pass if actual value is true, false or nil (respectively).
-
#be_a(klass)
(also: #be_an)
passes if target.kind_of?(klass).
-
#be_a_kind_of(expected)
(also: #be_kind_of, #a_kind_of)
Passes if actual.kind_of?(expected).
-
#be_an(klass)
Alias for #be_a.
-
#be_an_instance_of(expected)
(also: #be_instance_of, #an_instance_of)
Passes if actual.instance_of?(expected).
-
#be_between(min, max)
(also: #a_value_between)
Passes if actual.between?(min, max).
-
#be_falsey
(also: #be_falsy, #a_falsey_value, #a_falsy_value)
Passes if actual is falsey (false or nil).
-
#be_falsy
Alias for #be_falsey.
-
#be_instance_of(expected)
Alias for #be_an_instance_of.
-
#be_kind_of(expected)
Alias for #be_a_kind_of.
-
#be_nil
(also: #a_nil_value)
Passes if actual is nil.
-
#be_truthy
(also: #a_truthy_value)
Passes if actual is truthy (anything but false or nil).
-
#be_within(delta)
(also: #a_value_within, #within)
Passes if actual == expected +/- delta.
-
#change(receiver = nil, message = nil, &block)
(also: #a_block_changing, #changing)
Applied to a proc, specifies that its execution will cause some value to change.
-
#changing(receiver = nil, message = nil, &block)
Alias for #change.
-
#contain_exactly(*items)
(also: #a_collection_containing_exactly, #containing_exactly)
Passes if actual contains all of the expected regardless of order.
-
#containing_exactly(*items)
Alias for #contain_exactly.
-
#cover(*values)
(also: #a_range_covering, #covering)
Passes if actual covers expected.
-
#covering(*values)
Alias for #cover.
-
#end_with(*expected)
(also: #a_collection_ending_with, #a_string_ending_with, #ending_with)
Matches if the actual value ends with the expected value(s).
-
#ending_with(*expected)
Alias for #end_with.
-
#eq(expected)
(also: #an_object_eq_to, #eq_to)
Passes if
actual == expected
. -
#eq_to(expected)
Alias for #eq.
-
#eql(expected)
(also: #an_object_eql_to, #eql_to)
Passes if ‘actual.eql?(expected)`.
-
#eql_to(expected)
Alias for #eql.
-
#equal(expected)
(also: #an_object_equal_to, #equal_to)
Passes if
actual.equal?(expected)
(object identity). -
#equal_to(expected)
Alias for #equal.
-
#exist(*args)
(also: #an_object_existing, #existing)
Passes if
actual.exist?
oractual.exists?
-
#existing(*args)
Alias for #exist.
-
#expect ⇒ Expectations::ExpectationTarget
Supports ‘expect(actual).to matcher` syntax by wrapping
actual
in anExpectationTarget
. -
#have_attributes(expected)
(also: #an_object_having_attributes, #having_attributes)
Passes if actual’s attribute values match the expected attributes hash.
-
#having_attributes(expected)
Alias for #have_attributes.
-
#include(*expected)
(also: #a_collection_including, #a_string_including, #a_hash_including, #including)
Passes if actual includes expected.
-
#including(*expected)
Alias for #include.
-
#match(expected)
(also: #match_regex, #an_object_matching, #a_string_matching, #matching)
Given a
Regexp
orString
, passes if ‘actual.match(pattern)` Given an arbitrary nested data structure (e.g. -
#match_array(items)
(also: #an_array_matching)
An alternate form of #contain_exactly that accepts the expected contents as a single array arg rather than splatted out as individual items.
-
#match_regex(expected)
Alias for #match.
-
#matching(expected)
Alias for #match.
-
#output(expected = nil)
(also: #a_block_outputting)
With no arg, passes if the block outputs
to_stdout
orto_stderr
. -
#raise_error(error = BuiltIn::RaiseError::UndefinedValue, message = nil, &block)
(also: #raise_exception, #a_block_raising, #raising)
With no args, matches if any error is raised.
-
#raise_exception(error = BuiltIn::RaiseError::UndefinedValue, message = nil, &block)
Alias for #raise_error.
-
#raising(error = BuiltIn::RaiseError::UndefinedValue, message = nil, &block)
Alias for #raise_error.
-
#respond_to(*names)
(also: #an_object_responding_to, #responding_to)
Matches if the target object responds to all of the names provided.
-
#respond_to?(method) ⇒ Boolean
:nocov:
-
#responding_to(*names)
Alias for #respond_to.
-
#satisfy(description = nil, &block)
(also: #an_object_satisfying, #satisfying)
Passes if the submitted block returns true.
-
#satisfying(description = nil, &block)
Alias for #satisfy.
-
#start_with(*expected)
(also: #a_collection_starting_with, #a_string_starting_with, #starting_with)
Matches if the actual value starts with the expected value(s).
-
#starting_with(*expected)
Alias for #start_with.
-
#throw_symbol(expected_symbol = nil, expected_arg = nil)
(also: #a_block_throwing, #throwing)
Given no argument, matches if a proc throws any Symbol.
-
#throwing(expected_symbol = nil, expected_arg = nil)
Alias for #throw_symbol.
-
#within(delta)
Alias for #be_within.
-
#yield_control
(also: #a_block_yielding_control, #yielding_control)
Passes if the method called in the expect block yields, regardless of whether or not arguments are yielded.
-
#yield_successive_args(*args)
(also: #a_block_yielding_successive_args, #yielding_successive_args)
Designed for use with methods that repeatedly yield (such as iterators).
-
#yield_with_args(*args)
(also: #a_block_yielding_with_args, #yielding_with_args)
Given no arguments, matches if the method called in the expect block yields with arguments (regardless of what they are or how many there are).
-
#yield_with_no_args
(also: #a_block_yielding_with_no_args, #yielding_with_no_args)
Passes if the method called in the expect block yields with no arguments.
-
#yielding_control
Alias for #yield_control.
-
#yielding_successive_args(*args)
Alias for #yield_successive_args.
-
#yielding_with_args(*args)
Alias for #yield_with_args.
-
#yielding_with_no_args
Alias for #yield_with_no_args.
- #method_missing(method, *args, &block) private
- #respond_to_missing?(method) ⇒ Boolean private
Dynamic Method Handling
This class handles dynamic methods through the method_missing method
#method_missing(method, *args, &block) (private)
[ GitHub ]# File 'rspec-expectations/lib/rspec/matchers.rb', line 961
def method_missing(method, *args, &block) case method.to_s when BE_PREDICATE_REGEX BuiltIn::BePredicate.new(method, *args, &block) when HAS_REGEX BuiltIn::Has.new(method, *args, &block) else super end end
Class Attribute Details
.last_expectation_handler (rw)
# File 'rspec-expectations/lib/rspec/matchers/generated_descriptions.rb', line 5
attr_accessor :last_matcher, :last_expectation_handler
.last_matcher (rw)
# File 'rspec-expectations/lib/rspec/matchers/generated_descriptions.rb', line 5
attr_accessor :last_matcher, :last_expectation_handler
Class Method Details
.alias_matcher(new_name, old_name, options = {}, &description_override)
Extended from DSL#alias_matcher.
# File 'rspec-expectations/lib/rspec/matchers.rb', line 250
def self.alias_matcher(*args, &block) super(*args, &block) end
.append_features(mod) (private)
Note that included
doesn’t work for this because it is triggered after Matchers
is an ancestor of the inclusion host, rather than before, like append_features
. It’s important we check this before in order to find the cases where it was already previously included. :nocov:
# File 'rspec-expectations/lib/rspec/matchers.rb', line 1022
def append_features(mod) return super if mod < self # `mod < self` indicates a re-inclusion. subclasses = ObjectSpace.each_object(Class).select { |c| c < mod && c < self } return super unless subclasses.any? subclasses.reject! { |s| subclasses.any? { |s2| s < s2 } } # Filter to the root ancestor. subclasses = subclasses.map { |s| "`#{s}`" }.join(", ") RSpec.warning "`#{self}` has been included in a superclass (`#{mod}`) " \ "after previously being included in subclasses (#{subclasses}), " \ "which can trigger infinite recursion from `super` due to an MRI 1.9 bug " \ "(https://redmine.ruby-lang.org/issues/3351). To work around this, " \ "either upgrade to MRI 2.0+, include a dup of the module (e.g. " \ "`include #{self}.dup`), or find a way to include `#{self}` in `#{mod}` " \ "before it is included in subclasses (#{subclasses}). See " \ "https://github.com/rspec/rspec-expectations/issues/814 for more info" super end
.clear_generated_description
Used by rspec-core to clear the state used to generate descriptions after an example.
# File 'rspec-expectations/lib/rspec/matchers/generated_descriptions.rb', line 11
def self.clear_generated_description self.last_matcher = nil self.last_expectation_handler = nil end
.configuration ⇒ RSpec::Expectations::Configuration
Delegates to Expectations.configuration. This is here because rspec-core’s expect_with
option looks for a configuration
method on the mixin (‘RSpec::Matchers`) to yield to a block.
# File 'rspec-expectations/lib/rspec/matchers.rb', line 951
def self.configuration Expectations.configuration end
.define(name, &declarations)
Extended from DSL#define.
.define_negated_matcher(negated_name, base_name, &description_override)
Extended from DSL#define_negated_matcher.
.generated_description
Generates an an example description based on the last expectation. Used by rspec-core’s one-liner syntax.
# File 'rspec-expectations/lib/rspec/matchers/generated_descriptions.rb', line 19
def self.generated_description return nil if last_expectation_handler.nil? "#{last_expectation_handler.verb} #{last_description}" end
.is_a_describable_matcher?(obj) ⇒ Boolean
(private)
# File 'rspec-expectations/lib/rspec/matchers.rb', line 1008
def self.is_a_describable_matcher?(obj) is_a_matcher?(obj) && obj.respond_to?(:description) end
.is_a_matcher?(obj) ⇒ Boolean
(private)
# File 'rspec-expectations/lib/rspec/matchers.rb', line 988
def self.is_a_matcher?(obj) return true if ::RSpec::Matchers::BuiltIn::BaseMatcher === obj begin return false if obj.respond_to?(:i_respond_to_everything_so_im_not_really_a_matcher) rescue NoMethodError # Some objects, like BasicObject, don't implemented standard # reflection methods. return false end return false unless obj.respond_to?(:matches?) obj.respond_to?(: ) || obj.respond_to?(: ) # support legacy matchers end
.last_description
# File 'rspec-expectations/lib/rspec/matchers/generated_descriptions.rb', line 25
def self.last_description last_matcher.respond_to?(:description) ? last_matcher.description : <<-MESSAGE When you call a matcher in an example without a String, like this: specify { expect(object).to matcher } or this: it { is_expected.to matcher } RSpec expects the matcher to have a #description method. You should either add a String to the example this matcher is being used in, or give it a description method. Then you won't have to suffer this lengthy warning again. MESSAGE end
Instance Method Details
#a_block_changing(receiver = nil, message = nil, &block)
Alias for #change.
# File 'rspec-expectations/lib/rspec/matchers.rb', line 1
alias a_block_changing change
#a_block_outputting(expected = nil)
Alias for #output.
# File 'rspec-expectations/lib/rspec/matchers.rb', line 1
alias a_block_outputting output
#a_block_raising(error = BuiltIn::RaiseError::UndefinedValue, message = nil, &block)
Alias for #raise_error.
# File 'rspec-expectations/lib/rspec/matchers.rb', line 1
alias a_block_raising raise_error
#a_block_throwing(expected_symbol = nil, expected_arg = nil)
Alias for #throw_symbol.
# File 'rspec-expectations/lib/rspec/matchers.rb', line 1
alias a_block_throwing throw_symbol
#a_block_yielding_control
Alias for #yield_control.
# File 'rspec-expectations/lib/rspec/matchers.rb', line 1
alias a_block_yielding_control yield_control
#a_block_yielding_successive_args(*args)
Alias for #yield_successive_args.
# File 'rspec-expectations/lib/rspec/matchers.rb', line 1
alias a_block_yielding_successive_args yield_successive_args
#a_block_yielding_with_args(*args)
Alias for #yield_with_args.
# File 'rspec-expectations/lib/rspec/matchers.rb', line 1
alias a_block_yielding_with_args yield_with_args
#a_block_yielding_with_no_args
Alias for #yield_with_no_args.
# File 'rspec-expectations/lib/rspec/matchers.rb', line 1
alias a_block_yielding_with_no_args yield_with_no_args
#a_collection_containing_exactly(*items)
Alias for #contain_exactly.
# File 'rspec-expectations/lib/rspec/matchers.rb', line 1
alias a_collection_containing_exactly contain_exactly
#a_collection_ending_with(*expected)
Alias for #end_with.
# File 'rspec-expectations/lib/rspec/matchers.rb', line 1
alias a_collection_ending_with end_with
#a_collection_including(*expected)
Alias for #include.
# File 'rspec-expectations/lib/rspec/matchers.rb', line 1
alias a_collection_including include
#a_collection_starting_with(*expected)
Alias for #start_with.
# File 'rspec-expectations/lib/rspec/matchers.rb', line 1
alias a_collection_starting_with start_with
#a_falsey_value
Alias for #be_falsey.
# File 'rspec-expectations/lib/rspec/matchers.rb', line 1
alias a_falsey_value be_falsey
#a_falsy_value
Alias for #be_falsey.
# File 'rspec-expectations/lib/rspec/matchers.rb', line 1
alias a_falsy_value be_falsey
#a_hash_including(*expected)
Alias for #include.
# File 'rspec-expectations/lib/rspec/matchers.rb', line 1
alias a_hash_including include
#a_kind_of(expected)
Alias for #be_a_kind_of.
# File 'rspec-expectations/lib/rspec/matchers.rb', line 1
alias a_kind_of be_a_kind_of
#a_nil_value
Alias for #be_nil.
# File 'rspec-expectations/lib/rspec/matchers.rb', line 1
alias a_nil_value be_nil
#a_range_covering(*values)
Alias for #cover.
# File 'rspec-expectations/lib/rspec/matchers.rb', line 1
alias a_range_covering cover
#a_string_ending_with(*expected)
Alias for #end_with.
# File 'rspec-expectations/lib/rspec/matchers.rb', line 1
alias a_string_ending_with end_with
#a_string_including(*expected)
Alias for #include.
# File 'rspec-expectations/lib/rspec/matchers.rb', line 1
alias a_string_including include
#a_string_matching(expected)
Alias for #match.
# File 'rspec-expectations/lib/rspec/matchers.rb', line 1
alias a_string_matching match
#a_string_starting_with(*expected)
Alias for #start_with.
# File 'rspec-expectations/lib/rspec/matchers.rb', line 1
alias a_string_starting_with start_with
#a_truthy_value
Alias for #be_truthy.
# File 'rspec-expectations/lib/rspec/matchers.rb', line 1
alias a_truthy_value be_truthy
#a_value(*args)
Alias for #be.
# File 'rspec-expectations/lib/rspec/matchers.rb', line 1
alias a_value be
#a_value_between(min, max)
Alias for #be_between.
# File 'rspec-expectations/lib/rspec/matchers.rb', line 1
alias a_value_between be_between
#a_value_within(delta)
Alias for #be_within.
# File 'rspec-expectations/lib/rspec/matchers.rb', line 1
alias a_value_within be_within
#aggregate_failures(label = nil, metadata = {}) { ... }
The implementation of this feature uses a thread-local variable, which means that if you have an expectation failure in another thread, it’ll abort like normal.
Allows multiple expectations in the provided block to fail, and then aggregates them into a single exception, rather than aborting on the first expectation failure like normal. This allows you to see all failures from an entire set of expectations without splitting each off into its own example (which may slow things down if the example setup is expensive).
# File 'rspec-expectations/lib/rspec/matchers.rb', line 305
def aggregate_failures(label=nil, ={}, &block) Expectations::FailureAggregator.new(label, ).aggregate(&block) end
#all(expected)
The negative form ‘not_to all` is not supported. Instead use `not_to include` or pass a negative form of a matcher as the argument (e.g. `all exclude(:foo)`).
You can also use this with compound matchers as well.
Passes if the provided matcher passes when checked against all elements of the collection.
#an_array_matching(items)
Alias for #match_array.
# File 'rspec-expectations/lib/rspec/matchers.rb', line 1
alias an_array_matching match_array
#an_instance_of(expected)
Alias for #be_an_instance_of.
# File 'rspec-expectations/lib/rspec/matchers.rb', line 1
alias an_instance_of be_an_instance_of
#an_object_eq_to(expected)
Alias for #eq.
# File 'rspec-expectations/lib/rspec/matchers.rb', line 1
alias an_object_eq_to eq
#an_object_eql_to(expected)
Alias for #eql.
# File 'rspec-expectations/lib/rspec/matchers.rb', line 1
alias an_object_eql_to eql
#an_object_equal_to(expected)
Alias for #equal.
# File 'rspec-expectations/lib/rspec/matchers.rb', line 1
alias an_object_equal_to equal
#an_object_existing(*args)
Alias for #exist.
# File 'rspec-expectations/lib/rspec/matchers.rb', line 1
alias an_object_existing exist
#an_object_having_attributes(expected)
Alias for #have_attributes.
# File 'rspec-expectations/lib/rspec/matchers.rb', line 1
alias an_object_having_attributes have_attributes
#an_object_matching(expected)
Alias for #match.
# File 'rspec-expectations/lib/rspec/matchers.rb', line 1
alias an_object_matching match
#an_object_responding_to(*names)
Alias for #respond_to.
# File 'rspec-expectations/lib/rspec/matchers.rb', line 1
alias an_object_responding_to respond_to
#an_object_satisfying(description = nil, &block)
Alias for #satisfy.
# File 'rspec-expectations/lib/rspec/matchers.rb', line 1
alias satisfy
#be(*args) Also known as: #a_value
Given true, false, or nil, will pass if actual value is true, false or nil (respectively). Given no args means the caller should satisfy an if condition (to be or not to be).
Predicates are any Ruby method that ends in a “?” and returns true or false. Given be_ followed by arbitrary_predicate (without the “?”), ::RSpec
will match convert that into a query against the target object.
The arbitrary_predicate feature will handle any predicate prefixed with “be_an_” (e.g. be_an_instance_of), “be_a_” (e.g. be_a_kind_of) or “be_” (e.g. be_empty), letting you choose the prefix that best suits the predicate.
#be_a(klass) Also known as: #be_an
passes if target.kind_of?(klass)
# File 'rspec-expectations/lib/rspec/matchers.rb', line 355
def be_a(klass) be_a_kind_of(klass) end
#be_a_kind_of(expected) Also known as: #be_kind_of, #a_kind_of
Passes if actual.kind_of?(expected)
#be_an(klass)
Alias for #be_a.
# File 'rspec-expectations/lib/rspec/matchers.rb', line 358
alias_method :be_an, :be_a
#be_an_instance_of(expected) Also known as: #be_instance_of, #an_instance_of
Passes if actual.instance_of?(expected)
# File 'rspec-expectations/lib/rspec/matchers.rb', line 366
def be_an_instance_of(expected) BuiltIn::BeAnInstanceOf.new(expected) end
#be_between(min, max) Also known as: #a_value_between
Passes if actual.between?(min, max). Works with any Comparable object, including String, Symbol, Time, or Numeric (Fixnum, Bignum, Integer, Float, Complex, and Rational).
By default, be_between
is inclusive (i.e. passes when given either the max or min value), but you can make it exclusive
by chaining that off the matcher.
#be_falsey Also known as: #be_falsy, #a_falsey_value, #a_falsy_value
Passes if actual is falsey (false or nil)
#be_falsy
Alias for #be_falsey.
# File 'rspec-expectations/lib/rspec/matchers.rb', line 1
alias be_falsy be_falsey
#be_instance_of(expected)
Alias for #be_an_instance_of.
# File 'rspec-expectations/lib/rspec/matchers.rb', line 369
alias_method :be_instance_of, :be_an_instance_of
#be_kind_of(expected)
Alias for #be_a_kind_of.
# File 'rspec-expectations/lib/rspec/matchers.rb', line 381
alias_method :be_kind_of, :be_a_kind_of
#be_nil Also known as: #a_nil_value
Passes if actual is nil
#be_truthy Also known as: #a_truthy_value
Passes if actual is truthy (anything but false or nil)
#be_within(delta) Also known as: #a_value_within, #within
Passes if actual == expected +/- delta
#change(receiver = nil, message = nil, &block) Also known as: #a_block_changing, #changing
Applied to a proc, specifies that its execution will cause some value to change.
You can either pass receiver
and message
, or a block, but not both.
When passing a block, it must use the ‘{ … }` format, not do/end, as `{ … }` binds to the change
method, whereas do/end would errantly bind to the expect(..).to
or expect(…).not_to
method.
You can chain any of the following off of the end to specify details about the change:
-
from
-
to
or any one of:
-
by
-
by_at_least
-
by_at_most
Notes
Evaluates receiver.message
or block
before and after it evaluates the block passed to #expect. If the value is the same object, its before/after hash
value is used to see if it has changed. Therefore, your object needs to properly implement hash
to work correctly with this matcher.
‘expect( … ).not_to change` supports the form that specifies from
(which specifies what you expect the starting, unchanged value to be) but does not support forms with subsequent calls to by
, by_at_least
, by_at_most
or to
.
#changing(receiver = nil, message = nil, &block)
Alias for #change.
# File 'rspec-expectations/lib/rspec/matchers.rb', line 1
alias changing change
#contain_exactly(*items) Also known as: #a_collection_containing_exactly, #containing_exactly
This is also available using the =~
operator with should
, but =~
is not supported with #expect.
Passes if actual contains all of the expected regardless of order. This works for collections. Pass in multiple args and it will only pass if all args are found in collection.
# File 'rspec-expectations/lib/rspec/matchers.rb', line 510
def contain_exactly(*items) BuiltIn::ContainExactly.new(items) end
#containing_exactly(*items)
Alias for #contain_exactly.
# File 'rspec-expectations/lib/rspec/matchers.rb', line 1
alias containing_exactly contain_exactly
#cover(*values) Also known as: #a_range_covering, #covering
Passes if actual covers expected. This works for Ranges. You can also pass in multiple args and it will only pass if all args are found in Range.
Warning:: Ruby >= 1.9 only
#covering(*values)
Alias for #cover.
# File 'rspec-expectations/lib/rspec/matchers.rb', line 1
alias covering cover
#end_with(*expected) Also known as: #a_collection_ending_with, #a_string_ending_with, #ending_with
Matches if the actual value ends with the expected value(s). In the case of a string, matches against the last expected.length
characters of the actual string. In the case of an array, matches against the last expected.length
elements of the actual array.
#ending_with(*expected)
Alias for #end_with.
# File 'rspec-expectations/lib/rspec/matchers.rb', line 1
alias ending_with end_with
#eq(expected) Also known as: #an_object_eq_to, #eq_to
Passes if actual == expected
.
See www.ruby-doc.org/core/classes/Object.html#M001057 for more information about equality in Ruby.
#eq_to(expected)
Alias for #eq.
# File 'rspec-expectations/lib/rspec/matchers.rb', line 1
alias eq_to eq
#eql(expected) Also known as: #an_object_eql_to, #eql_to
Passes if ‘actual.eql?(expected)`
See www.ruby-doc.org/core/classes/Object.html#M001057 for more information about equality in Ruby.
#eql_to(expected)
Alias for #eql.
# File 'rspec-expectations/lib/rspec/matchers.rb', line 1
alias eql_to eql
#equal(expected) Also known as: #an_object_equal_to, #equal_to
Passes if actual.equal?(expected)
(object identity).
See www.ruby-doc.org/core/classes/Object.html#M001057 for more information about equality in Ruby.
#equal_to(expected)
Alias for #equal.
# File 'rspec-expectations/lib/rspec/matchers.rb', line 1
alias equal_to equal
#exist(*args) Also known as: #an_object_existing, #existing
Passes if actual.exist?
or actual.exists?
#existing(*args)
Alias for #exist.
# File 'rspec-expectations/lib/rspec/matchers.rb', line 1
alias existing exist
#expect ⇒ Expectations::ExpectationTarget
Supports ‘expect(actual).to matcher` syntax by wrapping actual
in an ExpectationTarget
.
#have_attributes(expected) Also known as: #an_object_having_attributes, #having_attributes
It will fail if actual doesn’t respond to any of the expected attributes.
Passes if actual’s attribute values match the expected attributes hash. This works no matter how you define your attribute readers.
# File 'rspec-expectations/lib/rspec/matchers.rb', line 616
def have_attributes(expected) BuiltIn::HaveAttributes.new(expected) end
#having_attributes(expected)
Alias for #have_attributes.
# File 'rspec-expectations/lib/rspec/matchers.rb', line 1
alias having_attributes have_attributes
#include(*expected) Also known as: #a_collection_including, #a_string_including, #a_hash_including, #including
Passes if actual includes expected. This works for collections and Strings. You can also pass in multiple args and it will only pass if all args are found in collection.
#including(*expected)
Alias for #include.
# File 'rspec-expectations/lib/rspec/matchers.rb', line 1
alias including include
#match(expected) Also known as: #match_regex, #an_object_matching, #a_string_matching, #matching
The #match_regex alias is deprecated and is not recommended for use. It was added in 2.12.1 to facilitate its use from within custom matchers (due to how the custom matcher Matchers::DSL
was evaluated in 2.x, match
could not be used there), but is no longer needed in 3.x.
Given a Regexp
or String
, passes if ‘actual.match(pattern)` Given an arbitrary nested data structure (e.g. arrays and hashes), matches if `expected === actual` || `actual == expected` for each pair of elements.
#match_array(items) Also known as: #an_array_matching
An alternate form of #contain_exactly that accepts the expected contents as a single array arg rather than splatted out as individual items.
# File 'rspec-expectations/lib/rspec/matchers.rb', line 715
def match_array(items) contain_exactly(*items) end
#match_regex(expected)
Alias for #match.
# File 'rspec-expectations/lib/rspec/matchers.rb', line 1
alias match_regex match
#matching(expected)
Alias for #match.
# File 'rspec-expectations/lib/rspec/matchers.rb', line 1
alias matching match
#output(expected = nil) Also known as: #a_block_outputting
to_stdout
and to_stderr
work by temporarily replacing $stdout
or $stderr
, so they’re not able to intercept stream output that explicitly uses ‘STDOUT`/`STDERR` or that uses a reference to `$stdout`/`$stderr` that was stored before the matcher was used.
to_stdout_from_any_process
and to_stderr_from_any_process
use Tempfiles, and are thus significantly (~30x) slower than to_stdout
and to_stderr
.
With no arg, passes if the block outputs to_stdout
or to_stderr
. With a string, passes if the block outputs that specific string to_stdout
or to_stderr
. With a regexp or matcher, passes if the block outputs a string to_stdout
or to_stderr
that matches.
To capture output from any spawned subprocess as well, use to_stdout_from_any_process
or to_stderr_from_any_process
. Output from any process that inherits the main process’s corresponding standard stream will be captured.
#raise_error(error = BuiltIn::RaiseError::UndefinedValue, message = nil, &block) Also known as: #raise_exception, #a_block_raising, #raising
With no args, matches if any error is raised. With a named error, matches only if that specific error is raised. With a named error and message specified as a String, matches only if both match. With a named error and message specified as a Regexp, matches only if both match. Pass an optional block to perform extra verifications on the exception matched
# File 'rspec-expectations/lib/rspec/matchers.rb', line 773
def raise_error(error=BuiltIn::RaiseError::UndefinedValue, =nil, &block) BuiltIn::RaiseError.new(error, , &block) end
#raise_exception(error = BuiltIn::RaiseError::UndefinedValue, message = nil, &block)
Alias for #raise_error.
# File 'rspec-expectations/lib/rspec/matchers.rb', line 776
alias_method :raise_exception, :raise_error
#raising(error = BuiltIn::RaiseError::UndefinedValue, message = nil, &block)
Alias for #raise_error.
# File 'rspec-expectations/lib/rspec/matchers.rb', line 1
alias raising raise_error
#respond_to(*names) Also known as: #an_object_responding_to, #responding_to
Matches if the target object responds to all of the names provided. Names can be Strings or Symbols.
#respond_to?(method) ⇒ Boolean
:nocov:
# File 'rspec-expectations/lib/rspec/matchers.rb', line 979
def respond_to?(method, *) method = method.to_s method =~ DYNAMIC_MATCHER_REGEX || super end
#respond_to_missing?(method) ⇒ Boolean
(private)
# File 'rspec-expectations/lib/rspec/matchers.rb', line 974
def respond_to_missing?(method, *) method =~ DYNAMIC_MATCHER_REGEX || super end
#responding_to(*names)
Alias for #respond_to.
# File 'rspec-expectations/lib/rspec/matchers.rb', line 1
alias responding_to respond_to
#satisfy(description = nil, &block) Also known as: #an_object_satisfying, #satisfying
Passes if the submitted block returns true. Yields target to the block.
Generally speaking, this should be thought of as a last resort when you can’t find any other way to specify the behaviour you wish to specify.
If you do find yourself in such a situation, you could always write a custom matcher, which would likely make your specs more expressive.
#satisfying(description = nil, &block)
Alias for #satisfy.
# File 'rspec-expectations/lib/rspec/matchers.rb', line 1
alias satisfy
#start_with(*expected) Also known as: #a_collection_starting_with, #a_string_starting_with, #starting_with
Matches if the actual value starts with the expected value(s). In the case of a string, matches against the first expected.length
characters of the actual string. In the case of an array, matches against the first expected.length
elements of the actual array.
#starting_with(*expected)
Alias for #start_with.
# File 'rspec-expectations/lib/rspec/matchers.rb', line 1
alias starting_with start_with
#throw_symbol(expected_symbol = nil, expected_arg = nil) Also known as: #a_block_throwing, #throwing
Given no argument, matches if a proc throws any Symbol.
Given a Symbol, matches if the given proc throws the specified Symbol.
Given a Symbol and an arg, matches if the given proc throws the specified Symbol with the specified arg.
# File 'rspec-expectations/lib/rspec/matchers.rb', line 850
def throw_symbol(expected_symbol=nil, expected_arg=nil) BuiltIn::ThrowSymbol.new(expected_symbol, expected_arg) end
#throwing(expected_symbol = nil, expected_arg = nil)
Alias for #throw_symbol.
# File 'rspec-expectations/lib/rspec/matchers.rb', line 1
alias throwing throw_symbol
#within(delta)
Alias for #be_within.
# File 'rspec-expectations/lib/rspec/matchers.rb', line 1
alias within be_within
#yield_control Also known as: #a_block_yielding_control, #yielding_control
Your expect block must accept a parameter and pass it on to the method-under-test as a block.
Passes if the method called in the expect block yields, regardless of whether or not arguments are yielded.
# File 'rspec-expectations/lib/rspec/matchers.rb', line 871
def yield_control BuiltIn::YieldControl.new end
#yield_successive_args(*args) Also known as: #a_block_yielding_successive_args, #yielding_successive_args
Your expect block must accept a parameter and pass it on to the method-under-test as a block.
Designed for use with methods that repeatedly yield (such as iterators). Passes if the method called in the expect block yields multiple times with arguments matching those given.
Argument matching is done using ===
(the case match operator) and ==
. If the expected and actual arguments match with either operator, the matcher will pass.
# File 'rspec-expectations/lib/rspec/matchers.rb', line 940
def yield_successive_args(*args) BuiltIn::YieldSuccessiveArgs.new(*args) end
#yield_with_args(*args) Also known as: #a_block_yielding_with_args, #yielding_with_args
Your expect block must accept a parameter and pass it on to the method-under-test as a block.
This matcher is not designed for use with methods that yield multiple times.
Given no arguments, matches if the method called in the expect block yields with arguments (regardless of what they are or how many there are).
Given arguments, matches if the method called in the expect block yields with arguments that match the given arguments.
Argument matching is done using ===
(the case match operator) and ==
. If the expected and actual arguments match with either operator, the matcher will pass.
# File 'rspec-expectations/lib/rspec/matchers.rb', line 919
def yield_with_args(*args) BuiltIn::YieldWithArgs.new(*args) end
#yield_with_no_args Also known as: #a_block_yielding_with_no_args, #yielding_with_no_args
Your expect block must accept a parameter and pass it on to the method-under-test as a block.
This matcher is not designed for use with methods that yield multiple times.
Passes if the method called in the expect block yields with no arguments. Fails if it does not yield, or yields with arguments.
# File 'rspec-expectations/lib/rspec/matchers.rb', line 889
def yield_with_no_args BuiltIn::YieldWithNoArgs.new end
#yielding_control
Alias for #yield_control.
# File 'rspec-expectations/lib/rspec/matchers.rb', line 1
alias yielding_control yield_control
#yielding_successive_args(*args)
Alias for #yield_successive_args.
# File 'rspec-expectations/lib/rspec/matchers.rb', line 1
alias yielding_successive_args yield_successive_args
#yielding_with_args(*args)
Alias for #yield_with_args.
# File 'rspec-expectations/lib/rspec/matchers.rb', line 1
alias yielding_with_args yield_with_args
#yielding_with_no_args
Alias for #yield_with_no_args.
# File 'rspec-expectations/lib/rspec/matchers.rb', line 1
alias yielding_with_no_args yield_with_no_args