Module: RSpec::Matchers
- Extended by:
- DSL
- Included in:
- DSL::Matcher
- Defined in:
- lib/rspec/matchers.rb,
lib/rspec/matchers/dsl.rb,
lib/rspec/matchers/pretty.rb,
lib/rspec/matchers/matcher.rb,
lib/rspec/matchers/be_close.rb,
lib/rspec/matchers/built_in.rb,
lib/rspec/matchers/built_in/be.rb,
lib/rspec/matchers/built_in/eq.rb,
lib/rspec/matchers/built_in/eql.rb,
lib/rspec/matchers/built_in/has.rb,
lib/rspec/matchers/built_in/have.rb,
lib/rspec/matchers/configuration.rb,
lib/rspec/matchers/built_in/cover.rb,
lib/rspec/matchers/built_in/equal.rb,
lib/rspec/matchers/built_in/exist.rb,
lib/rspec/matchers/built_in/match.rb,
lib/rspec/matchers/built_in/yield.rb,
lib/rspec/matchers/method_missing.rb,
lib/rspec/matchers/built_in/change.rb,
lib/rspec/matchers/built_in/include.rb,
lib/rspec/matchers/built_in/satisfy.rb,
lib/rspec/matchers/operator_matcher.rb,
lib/rspec/matchers/built_in/be_within.rb,
lib/rspec/matchers/built_in/be_kind_of.rb,
lib/rspec/matchers/built_in/respond_to.rb,
lib/rspec/matchers/built_in/match_array.rb,
lib/rspec/matchers/built_in/raise_error.rb,
lib/rspec/matchers/built_in/base_matcher.rb,
lib/rspec/matchers/built_in/throw_symbol.rb,
lib/rspec/matchers/generated_descriptions.rb,
lib/rspec/matchers/built_in/be_instance_of.rb,
lib/rspec/matchers/built_in/start_and_end_with.rb,
lib/rspec/matchers/extensions/instance_eval_with_args.rb
Overview
RSpec::Matchers provides a number of useful matchers we use to define expectations. A matcher is any object that responds to the following:
matches?(actual)
These methods are also part of the matcher protocol, but are optional:
does_not_match?(actual)
description
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 addtion 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(Fixnum) # => 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(Fixnum) # => 3.instance_of?(Fixnum) | 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.
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_for_should and failure_message_for_should_not) 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 required from your spec file(s):
RSpec::configure do |config|
config.include(CustomGameMatchers)
end
Defined Under Namespace
Modules: BuiltIn, DSL, Extensions, Pretty Classes: Configuration, OperatorMatcher
Class Attribute Summary collapse
-
.last_matcher ⇒ Object
Returns the value of attribute last_matcher.
-
.last_should ⇒ Object
Returns the value of attribute last_should.
Class Method Summary collapse
- .clear_generated_description ⇒ Object
-
.configuration ⇒ RSpec::Matchers::Configuration
The configuration object.
- .generated_description ⇒ Object
- .is_a_matcher?(obj) ⇒ Boolean private
Instance Method Summary collapse
-
#be(*args) ⇒ Object
Given true, false, or nil, will pass if actual value is true, false or nil (respectively).
-
#be_a(klass) ⇒ Object
(also: #be_an)
passes if target.kind_of?(klass).
-
#be_a_kind_of(expected) ⇒ Object
(also: #be_kind_of)
Passes if actual.kind_of?(expected).
-
#be_an_instance_of(expected) ⇒ Object
(also: #be_instance_of)
Passes if actual.instance_of?(expected).
-
#be_close(expected, delta) ⇒ Object
deprecated
Deprecated.
use +be_within+ instead.
-
#be_false ⇒ Object
Passes if actual is falsy (false or nil).
-
#be_nil ⇒ Object
Passes if actual is nil.
-
#be_true ⇒ Object
Passes if actual is truthy (anything but false or nil).
-
#be_within(delta) ⇒ Object
Passes if actual == expected +/- delta.
-
#change(receiver = nil, message = nil, &block) ⇒ Object
Applied to a proc, specifies that its execution will cause some value to change.
-
#cover(*values) ⇒ Object
Passes if actual covers expected.
-
#end_with(*expected) ⇒ Object
Matches if the actual value ends with the expected value(s).
-
#eq(expected) ⇒ Object
Passes if actual == expected.
-
#eql(expected) ⇒ Object
Passes if +actual.eql?(expected)+.
-
#equal(expected) ⇒ Object
Passes if actual.equal?(expected) (object identity).
-
#exist(*args) ⇒ Object
Passes if
actual.exist?oractual.exists?. -
#have(n) ⇒ Object
(also: #have_exactly)
Passes if receiver is a collection with the submitted number of items OR if the receiver OWNS a collection with the submitted number of items.
-
#have_at_least(n) ⇒ Object
Exactly like have() with >=.
-
#have_at_most(n) ⇒ Object
Exactly like have() with <=.
-
#include(*expected) ⇒ Object
Passes if actual includes expected.
-
#match(expected) ⇒ Object
(also: #match_regex)
Given a Regexp or String, passes if actual.match(pattern).
-
#match_array(array) ⇒ Object
Passes if actual contains all of the expected regardless of order.
-
#raise_error(error = Exception, message = nil, &block) ⇒ Object
(also: #raise_exception)
With no args, matches if any error is raised.
-
#respond_to(*names) ⇒ Object
Matches if the target object responds to all of the names provided.
-
#satisfy(&block) ⇒ Object
Passes if the submitted block returns true.
-
#start_with(*expected) ⇒ Object
Matches if the actual value starts with the expected value(s).
-
#throw_symbol(expected_symbol = nil, expected_arg = nil) ⇒ Object
Given no argument, matches if a proc throws any Symbol.
-
#yield_control ⇒ Object
Passes if the method called in the expect block yields, regardless of whether or not arguments are yielded.
-
#yield_successive_args(*args) ⇒ Object
Designed for use with methods that repeatedly yield (such as iterators).
-
#yield_with_args(*args) ⇒ Object
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 ⇒ Object
Passes if the method called in the expect block yields with no arguments.
Methods included from DSL
Dynamic Method Handling
This class handles dynamic methods through the method_missing method
#method_missing(method, *args, &block) ⇒ Object (private)
6 7 8 9 10 |
# File 'lib/rspec/matchers/method_missing.rb', line 6 def method_missing(method, *args, &block) return Matchers::BuiltIn::BePredicate.new(method, *args, &block) if method.to_s =~ /^be_/ return Matchers::BuiltIn::Has.new(method, *args, &block) if method.to_s =~ /^have_/ super end |
Class Attribute Details
.last_matcher ⇒ Object
Returns the value of attribute last_matcher.
4 5 6 |
# File 'lib/rspec/matchers/generated_descriptions.rb', line 4 def last_matcher @last_matcher end |
.last_should ⇒ Object
Returns the value of attribute last_should.
4 5 6 |
# File 'lib/rspec/matchers/generated_descriptions.rb', line 4 def last_should @last_should end |
Class Method Details
.clear_generated_description ⇒ Object
7 8 9 10 |
# File 'lib/rspec/matchers/generated_descriptions.rb', line 7 def self.clear_generated_description self.last_matcher = nil self.last_should = nil end |
.configuration ⇒ RSpec::Matchers::Configuration
The configuration object
100 101 102 |
# File 'lib/rspec/matchers/configuration.rb', line 100 def self.configuration @configuration ||= Configuration.new end |
.generated_description ⇒ Object
12 13 14 15 |
# File 'lib/rspec/matchers/generated_descriptions.rb', line 12 def self.generated_description return nil if last_should.nil? "#{last_should.to_s.gsub('_',' ')} #{last_description}" end |
.is_a_matcher?(obj) ⇒ Boolean
This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.
178 179 180 181 182 183 184 |
# File 'lib/rspec/matchers.rb', line 178 def self.is_a_matcher?(obj) return true if ::RSpec::Matchers::BuiltIn::BaseMatcher === obj return false if obj.respond_to?(:i_respond_to_everything_so_im_not_really_a_matcher) return false unless obj.respond_to?(:matches?) obj.respond_to?(:failure_message_for_should) || obj.respond_to?(:failure_message) end |
Instance Method Details
#be(*args) ⇒ Object
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.
221 222 223 224 |
# File 'lib/rspec/matchers.rb', line 221 def be(*args) args.empty? ? Matchers::BuiltIn::Be.new : equal(*args) end |
#be_a(klass) ⇒ Object Also known as: be_an
passes if target.kind_of?(klass)
227 228 229 |
# File 'lib/rspec/matchers.rb', line 227 def be_a(klass) be_a_kind_of(klass) end |
#be_a_kind_of(expected) ⇒ Object Also known as: be_kind_of
Passes if actual.kind_of?(expected)
253 254 255 |
# File 'lib/rspec/matchers.rb', line 253 def be_a_kind_of(expected) BuiltIn::BeAKindOf.new(expected) end |
#be_an_instance_of(expected) ⇒ Object Also known as: be_instance_of
Passes if actual.instance_of?(expected)
240 241 242 |
# File 'lib/rspec/matchers.rb', line 240 def be_an_instance_of(expected) BuiltIn::BeAnInstanceOf.new(expected) end |
#be_close(expected, delta) ⇒ Object
use +be_within+ instead.
4 5 6 7 |
# File 'lib/rspec/matchers/be_close.rb', line 4 def be_close(expected, delta) RSpec.deprecate("be_close(#{expected}, #{delta})", :replacement => "be_within(#{delta}).of(#{expected})") be_within(delta).of(expected) end |
#be_false ⇒ Object
Passes if actual is falsy (false or nil)
192 193 194 |
# File 'lib/rspec/matchers.rb', line 192 def be_false BuiltIn::BeFalse.new end |
#be_nil ⇒ Object
Passes if actual is nil
197 198 199 |
# File 'lib/rspec/matchers.rb', line 197 def be_nil BuiltIn::BeNil.new end |
#be_true ⇒ Object
Passes if actual is truthy (anything but false or nil)
187 188 189 |
# File 'lib/rspec/matchers.rb', line 187 def be_true BuiltIn::BeTrue.new end |
#be_within(delta) ⇒ Object
Passes if actual == expected +/- delta
265 266 267 |
# File 'lib/rspec/matchers.rb', line 265 def be_within(delta) BuiltIn::BeWithin.new(delta) end |
#change(receiver = nil, message = nil, &block) ⇒ Object
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(..)+ or +expect(..).not_to+ method.
== Notes
Evaluates receiver.message or block before and after it evaluates the block passed to expect.
expect( ... ).not_to change only supports the form with no subsequent calls to by, by_at_least, by_at_most, to or from.
335 336 337 |
# File 'lib/rspec/matchers.rb', line 335 def change(receiver=nil, =nil, &block) BuiltIn::Change.new(receiver, , &block) end |
#cover(*values) ⇒ Object
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
351 352 353 |
# File 'lib/rspec/matchers.rb', line 351 def cover(*values) BuiltIn::Cover.new(*values) end |
#end_with(*expected) ⇒ Object
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.
365 366 367 |
# File 'lib/rspec/matchers.rb', line 365 def end_with(*expected) BuiltIn::EndWith.new(*expected) end |
#eq(expected) ⇒ Object
Passes if actual == expected.
See http://www.ruby-doc.org/core/classes/Object.html#M001057 for more information about equality in Ruby.
378 379 380 |
# File 'lib/rspec/matchers.rb', line 378 def eq(expected) BuiltIn::Eq.new(expected) end |
#eql(expected) ⇒ Object
Passes if +actual.eql?(expected)+
See http://www.ruby-doc.org/core/classes/Object.html#M001057 for more information about equality in Ruby.
391 392 393 |
# File 'lib/rspec/matchers.rb', line 391 def eql(expected) BuiltIn::Eql.new(expected) end |
#equal(expected) ⇒ Object
Passes if actual.equal?(expected) (object identity).
See http://www.ruby-doc.org/core/classes/Object.html#M001057 for more information about equality in Ruby.
404 405 406 |
# File 'lib/rspec/matchers.rb', line 404 def equal(expected) BuiltIn::Equal.new(expected) end |
#exist(*args) ⇒ Object
Passes if actual.exist? or actual.exists?
412 413 414 |
# File 'lib/rspec/matchers.rb', line 412 def exist(*args) BuiltIn::Exist.new(*args) end |
#have(n) ⇒ Object Also known as: have_exactly
Passes if receiver is a collection with the submitted number of items OR if the receiver OWNS a collection with the submitted number of items.
If the receiver OWNS the collection, you must use the name of the
collection. So if a Team instance has a collection named #players,
you must use that name to set the expectation.
If the receiver IS the collection, you can use any name you like for
named_collection. We'd recommend using either "elements", "members", or
"items" as these are all standard ways of describing the things IN a
collection.
This also works for Strings, letting you set expectations about their lengths.
444 445 446 |
# File 'lib/rspec/matchers.rb', line 444 def have(n) BuiltIn::Have.new(n) end |
#have_at_least(n) ⇒ Object
Exactly like have() with >=.
Warning:
expect(..).not_to have_at_least is not supported
457 458 459 |
# File 'lib/rspec/matchers.rb', line 457 def have_at_least(n) BuiltIn::Have.new(n, :at_least) end |
#have_at_most(n) ⇒ Object
Exactly like have() with <=.
Warning:
expect(..).not_to have_at_most is not supported
469 470 471 |
# File 'lib/rspec/matchers.rb', line 469 def have_at_most(n) BuiltIn::Have.new(n, :at_most) end |
#include(*expected) ⇒ Object
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.
485 486 487 |
# File 'lib/rspec/matchers.rb', line 485 def include(*expected) BuiltIn::Include.new(*expected) end |
#match(expected) ⇒ Object Also known as: match_regex
Due to Ruby's method dispatch mechanism, using the #match matcher
Given a Regexp or String, passes if actual.match(pattern)
within a custom matcher defined via the matcher DSL
(RSpec::Matcher.define) will result Ruby calling the wrong #match
method and raising an ArgumentError. Instead, use the aliased
#match_regex method.
503 504 505 |
# File 'lib/rspec/matchers.rb', line 503 def match(expected) BuiltIn::Match.new(expected) end |
#match_array(array) ⇒ Object
This is also available using the =~ operator with should,
but =~ is not supported with expect.
This matcher only supports positive expectations. expect(..).not_to match_array(other_array) is not supported.
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.
688 689 690 |
# File 'lib/rspec/matchers.rb', line 688 def match_array(array) BuiltIn::MatchArray.new(array) end |
#raise_error(error = Exception, message = nil, &block) ⇒ Object Also known as: raise_exception
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 messsage specified as a String, matches only if both match. With a named error and messsage specified as a Regexp, matches only if both match. Pass an optional block to perform extra verifications on the exception matched
524 525 526 |
# File 'lib/rspec/matchers.rb', line 524 def raise_error(error=Exception, =nil, &block) BuiltIn::RaiseError.new(error, , &block) end |
#respond_to(*names) ⇒ Object
Matches if the target object responds to all of the names provided. Names can be Strings or Symbols.
expect("string").to respond_to(:length)
537 538 539 |
# File 'lib/rspec/matchers.rb', line 537 def respond_to(*names) BuiltIn::RespondTo.new(*names) end |
#satisfy(&block) ⇒ Object
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.
554 555 556 |
# File 'lib/rspec/matchers.rb', line 554 def satisfy(&block) BuiltIn::Satisfy.new(&block) end |
#start_with(*expected) ⇒ Object
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.
568 569 570 |
# File 'lib/rspec/matchers.rb', line 568 def start_with(*expected) BuiltIn::StartWith.new(*expected) end |
#throw_symbol(expected_symbol = nil, expected_arg = nil) ⇒ Object
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.
588 589 590 |
# File 'lib/rspec/matchers.rb', line 588 def throw_symbol(expected_symbol=nil, expected_arg=nil) BuiltIn::ThrowSymbol.new(expected_symbol, expected_arg) end |
#yield_control ⇒ Object
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, regardless of whether or not arguments are yielded.
604 605 606 |
# File 'lib/rspec/matchers.rb', line 604 def yield_control BuiltIn::YieldControl.new end |
#yield_successive_args(*args) ⇒ Object
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.
670 671 672 |
# File 'lib/rspec/matchers.rb', line 670 def yield_successive_args(*args) BuiltIn::YieldSuccessiveArgs.new(*args) end |
#yield_with_args(*args) ⇒ Object
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.
650 651 652 |
# File 'lib/rspec/matchers.rb', line 650 def yield_with_args(*args) BuiltIn::YieldWithArgs.new(*args) end |
#yield_with_no_args ⇒ Object
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.
621 622 623 |
# File 'lib/rspec/matchers.rb', line 621 def yield_with_no_args BuiltIn::YieldWithNoArgs.new end |