Module: RSpec::Matchers
- Included in:
- DSL::Matcher
- Defined in:
- lib/rspec/matchers.rb,
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/eq.rb,
lib/rspec/matchers/built_in/be.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/block_aliases.rb,
lib/rspec/matchers/built_in/equal.rb,
lib/rspec/matchers/built_in/exist.rb,
lib/rspec/matchers/built_in/cover.rb,
lib/rspec/matchers/method_missing.rb,
lib/rspec/matchers/built_in/match.rb,
lib/rspec/matchers/built_in/change.rb,
lib/rspec/matchers/built_in/include.rb,
lib/rspec/matchers/operator_matcher.rb,
lib/rspec/matchers/built_in/satisfy.rb,
lib/rspec/matchers/built_in/be_within.rb,
lib/rspec/matchers/built_in/respond_to.rb,
lib/rspec/matchers/built_in/be_kind_of.rb,
lib/rspec/matchers/built_in/match_array.rb,
lib/rspec/matchers/built_in/raise_error.rb,
lib/rspec/matchers/built_in/throw_symbol.rb,
lib/rspec/matchers/built_in/base_matcher.rb,
lib/rspec/matchers/generated_descriptions.rb,
lib/rspec/matchers/built_in/be_instance_of.rb,
lib/rspec/matchers/extensions/instance_eval_with_args.rb
Overview
RSpec::Matchers provides a number of useful matchers we use to compose 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 should be_ followed by the predicate without
the question mark, and RSpec will figure it out from there. For example:
[].should be_empty # => [].empty?() | passes
[].should_not be_empty # => [].empty?() | fails
In addtion to prefixing the predicate matchers with "be", you can also use "be_a" and "bean", making your specs read much more naturally:
"a string".should be_an_instance_of(String) =>"a string".instance_of?(String) #passes
3.should be_a_kind_of(Fixnum) # => 3.kind_of?(Numeric) | passes
3.should be_a_kind_of(Numeric) # => 3.kind_of?(Numeric) | passes
3.should be_an_instance_of(Fixnum) # => 3.instance_of?(Fixnum) | passes
3.should_not be_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:
{:a => "A"}.should have_key(:a) # => {:a => "A"}.has_key?(:a) | passes
{:a => "A"}.should have_key(:b) # => {:a => "A"}.has_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:
bob.current_zone.should eql(Zone.new("4"))
But you might find it more expressive to say:
bob.should be_in_zone("4")
and/or
bob.should_not 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 should or should_not).
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: BlockAliases, BuiltIn, DSL, Extensions, Pretty Classes: OperatorMatcher
Class Attribute Summary (collapse)
-
+ (Object) last_matcher
Returns the value of attribute last_matcher.
-
+ (Object) last_should
Returns the value of attribute last_should.
Class Method Summary (collapse)
Instance Method Summary (collapse)
-
- (Object) Array
Passes if actual contains all of the expected regardless of order.
-
- (Object) be(*args)
Given true, false, or nil, will pass if actual value is true, false or nil (respectively).
-
- (Object) be_a(klass)
(also: #be_an)
passes if target.kind_of?(klass).
-
- (Object) be_a_kind_of(expected)
(also: #be_kind_of)
Passes if actual.kind_of?(expected).
-
- (Object) be_an_instance_of(expected)
(also: #be_instance_of)
Passes if actual.instance_of?(expected).
-
- (Object) be_close(expected, delta)
Deprecated
Deprecated.
use +be_within+ instead.
-
- (Object) be_false
Passes if actual is falsy (false or nil).
-
- (Object) be_nil
Passes if actual is nil.
-
- (Object) be_true
Passes if actual is truthy (anything but false or nil).
-
- (Object) be_within(delta)
Passes if actual == expected +/- delta.
-
- (Object) change(receiver = nil, message = nil, &block)
Applied to a proc, specifies that its execution will cause some value to change.
- - (Object) cover(*values)
-
- (Object) eq(expected)
Passes if actual == expected.
-
- (Object) eql(expected)
Passes if +actual.eql?(expected)+.
-
- (Object) equal(expected)
Passes if actual.equal?(expected) (object identity).
-
- (Object) exist(*args)
Passes if
actual.exist?oractual.exists?. -
- (Object) expect(&block)
Extends the submitted block with aliases to and to_not for should and should_not.
-
- (Object) have(n)
(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.
-
- (Object) have_at_least(n)
Exactly like have() with >=.
-
- (Object) have_at_most(n)
Exactly like have() with <=.
-
- (Object) include(*expected)
Passes if actual includes expected.
-
- (Object) match(expected)
Given a Regexp or String, passes if actual.match(pattern).
-
- (Object) raise_error(error = Exception, message = nil, &block)
(also: #raise_exception)
With no args, matches if any error is raised.
-
- (Object) respond_to(*names)
Matches if the target object responds to all of the names provided.
-
- (Object) satisfy(&block)
Passes if the submitted block returns true.
-
- (Object) throw_symbol(expected_symbol = nil, expected_arg = nil)
Given no argument, matches if a proc throws any Symbol.
Dynamic Method Handling
This class handles dynamic methods through the method_missing method
- (Object) method_missing(method, *args, &block) (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
+ (Object) last_matcher
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 |
+ (Object) last_should
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
+ (Object) clear_generated_description
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 |
+ (Object) generated_description
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 |
Instance Method Details
- (Object) Array
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.
NOTE: there is no should_not version of array.should =~ other_array
570 |
# File 'lib/rspec/matchers.rb', line 570 OperatorMatcher.register(Array, '=~', BuiltIn::MatchArray) |
- (Object) be(*args)
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 arbitrarypredicate feature will handle any predicate prefixed with "be_an" (e.g. bean_instance_of), "be_a" (e.g. bea_kind_of) or "be" (e.g. be_empty), letting you choose the prefix that best suits the predicate.
228 229 230 231 |
# File 'lib/rspec/matchers.rb', line 228 def be(*args) args.empty? ? Matchers::BuiltIn::Be.new : equal(*args) end |
- (Object) be_a(klass) Also known as: be_an
passes if target.kind_of?(klass)
234 235 236 |
# File 'lib/rspec/matchers.rb', line 234 def be_a(klass) be_a_kind_of(klass) end |
- (Object) be_a_kind_of(expected) Also known as: be_kind_of
Passes if actual.kind_of?(expected)
260 261 262 |
# File 'lib/rspec/matchers.rb', line 260 def be_a_kind_of(expected) BuiltIn::BeAKindOf.new(expected) end |
- (Object) be_an_instance_of(expected) Also known as: be_instance_of
Passes if actual.instance_of?(expected)
247 248 249 |
# File 'lib/rspec/matchers.rb', line 247 def be_an_instance_of(expected) BuiltIn::BeAnInstanceOf.new(expected) end |
- (Object) be_close(expected, delta)
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})", "be_within(#{delta}).of(#{expected})") be_within(delta).of(expected) end |
- (Object) be_false
Passes if actual is falsy (false or nil)
199 200 201 |
# File 'lib/rspec/matchers.rb', line 199 def be_false BuiltIn::BeFalse.new end |
- (Object) be_nil
Passes if actual is nil
204 205 206 |
# File 'lib/rspec/matchers.rb', line 204 def be_nil BuiltIn::BeNil.new end |
- (Object) be_true
Passes if actual is truthy (anything but false or nil)
194 195 196 |
# File 'lib/rspec/matchers.rb', line 194 def be_true BuiltIn::BeTrue.new end |
- (Object) be_within(delta)
Passes if actual == expected +/- delta
272 273 274 |
# File 'lib/rspec/matchers.rb', line 272 def be_within(delta) BuiltIn::BeWithin.new(delta) end |
- (Object) change(receiver = nil, message = nil, &block)
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 +should+ or +should_not+ method.
== Notes
Evaluates receiver.message or block before and after it evaluates the proc object (generated by the lambdas in the examples above).
should_not change only supports the form with no subsequent calls to by, by_at_least, by_at_most, to or from.
338 339 340 |
# File 'lib/rspec/matchers.rb', line 338 def change(receiver=nil, =nil, &block) BuiltIn::Change.new(receiver, , &block) end |
- (Object) cover(*values)
354 355 356 |
# File 'lib/rspec/matchers.rb', line 354 def cover(*values) BuiltIn::Cover.new(*values) end |
- (Object) eq(expected)
Passes if actual == expected.
See http://www.ruby-doc.org/core/classes/Object.html#M001057 for more information about equality in Ruby.
366 367 368 |
# File 'lib/rspec/matchers.rb', line 366 def eq(expected) BuiltIn::Eq.new(expected) end |
- (Object) eql(expected)
Passes if +actual.eql?(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 eql(expected) BuiltIn::Eql.new(expected) end |
- (Object) equal(expected)
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.
390 391 392 |
# File 'lib/rspec/matchers.rb', line 390 def equal(expected) BuiltIn::Equal.new(expected) end |
- (Object) exist(*args)
Passes if actual.exist? or actual.exists?
398 399 400 |
# File 'lib/rspec/matchers.rb', line 398 def exist(*args) BuiltIn::Exist.new(*args) end |
- (Object) expect(&block)
Extends the submitted block with aliases to and to_not for should and should_not.
15 16 17 |
# File 'lib/rspec/matchers/block_aliases.rb', line 15 def expect(&block) block.extend BlockAliases end |
- (Object) have(n) 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.
430 431 432 |
# File 'lib/rspec/matchers.rb', line 430 def have(n) BuiltIn::Have.new(n) end |
- (Object) have_at_least(n)
Exactly like have() with >=.
Warning:
should_not have_at_least is not supported
443 444 445 |
# File 'lib/rspec/matchers.rb', line 443 def have_at_least(n) BuiltIn::Have.new(n, :at_least) end |
- (Object) have_at_most(n)
Exactly like have() with <=.
Warning:
should_not have_at_most is not supported
455 456 457 |
# File 'lib/rspec/matchers.rb', line 455 def have_at_most(n) BuiltIn::Have.new(n, :at_most) end |
- (Object) include(*expected)
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.
471 472 473 |
# File 'lib/rspec/matchers.rb', line 471 def include(*expected) BuiltIn::Include.new(*expected) end |
- (Object) match(expected)
Given a Regexp or String, passes if actual.match(pattern)
481 482 483 |
# File 'lib/rspec/matchers.rb', line 481 def match(expected) BuiltIn::Match.new(expected) end |
- (Object) raise_error(error = Exception, message = nil, &block) 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
503 504 505 |
# File 'lib/rspec/matchers.rb', line 503 def raise_error(error=Exception, =nil, &block) BuiltIn::RaiseError.new(error, , &block) end |
- (Object) respond_to(*names)
Matches if the target object responds to all of the names provided. Names can be Strings or Symbols.
514 515 516 |
# File 'lib/rspec/matchers.rb', line 514 def respond_to(*names) BuiltIn::RespondTo.new(*names) end |
- (Object) satisfy(&block)
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.
533 534 535 |
# File 'lib/rspec/matchers.rb', line 533 def satisfy(&block) BuiltIn::Satisfy.new(&block) end |
- (Object) throw_symbol(expected_symbol = nil, expected_arg = nil)
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.
553 554 555 |
# File 'lib/rspec/matchers.rb', line 553 def throw_symbol(expected_symbol=nil, expected_arg=nil) BuiltIn::ThrowSymbol.new(expected_symbol, expected_arg) end |