Module: Spec::Matchers
- Defined in:
- lib/spec/matchers.rb,
lib/spec/matchers/be.rb,
lib/spec/matchers/eql.rb,
lib/spec/matchers/has.rb,
lib/spec/matchers/have.rb,
lib/spec/matchers/equal.rb,
lib/spec/matchers/match.rb,
lib/spec/matchers/change.rb,
lib/spec/matchers/include.rb,
lib/spec/matchers/satisfy.rb,
lib/spec/matchers/be_close.rb,
lib/spec/matchers/respond_to.rb,
lib/spec/matchers/raise_error.rb,
lib/spec/matchers/throw_symbol.rb
Overview
RSpec ships with a number of useful Expression Matchers. An Expression Matcher is any object that responds to the following methods:
matches?(actual)
#optional
description #optional
See Spec::Expectations to learn how to use these as Expectation Matchers. See Spec::Mocks to learn how to use them as Mock Argument Constraints.
Predicates
In addition to those Expression 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 “be_an_”, 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 Expression Matchers
When you find that none of the stock Expression Matchers provide a natural feeling expectation, you can very easily write your own.
For example, 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")
To do this, you would need to write a class like this:
class BeInZone
def initialize(expected)
@expected = expected
end
def matches?(actual)
@actual = actual
bob.current_zone.eql?(Zone.new(@expected))
end
def
"expected #{@actual.inspect} to be in Zone #{@expected}"
end
def
"expected #{@actual.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
context "Player behaviour" do
include CustomGameMatchers
...
end
Defined Under Namespace
Classes: Be, BeClose, Change, Eql, Equal, Has, Have, Include, Match, MatcherError, RaiseError, RespondTo, Satisfy, ThrowSymbol
Class Method Summary collapse
Instance Method Summary collapse
-
#be(*args) ⇒ Object
:call-seq: should be_true should be_false should be_nil should be_arbitrary_predicate(*args) should_not be_nil should_not be_arbitrary_predicate(*args).
-
#be_close(expected, delta) ⇒ Object
:call-seq: should be_close(expected, delta) should_not be_close(expected, delta).
-
#change(target = nil, message = nil, &block) ⇒ Object
:call-seq: should change(receiver, message, &block) should change(receiver, message, &block).by(value) should change(receiver, message, &block).from(old).to(new) should_not change(receiver, message, &block).
-
#eql(expected) ⇒ Object
:call-seq: should eql(expected) should_not eql(expected).
-
#equal(expected) ⇒ Object
:call-seq: should equal(expected) should_not equal(expected).
-
#have(n) ⇒ Object
(also: #have_exactly)
:call-seq: should have(number).named_collection__or__sugar should_not have(number).named_collection__or__sugar.
-
#have_at_least(n) ⇒ Object
:call-seq: should have_at_least(number).items.
-
#have_at_most(n) ⇒ Object
:call-seq: should have_at_most(number).items.
-
#include(expected) ⇒ Object
:call-seq: should include(expected) should_not include(expected).
-
#match(regexp) ⇒ Object
:call-seq: should match(regexp) should_not match(regexp).
-
#method_missing(sym, *args, &block) ⇒ Object
:nodoc:.
-
#raise_error(error = Exception, message = nil) ⇒ Object
:call-seq: should raise_error() should raise_error(NamedError) should raise_error(NamedError, String) should raise_error(NamedError, Regexp) should_not raise_error() should_not raise_error(NamedError) should_not raise_error(NamedError, String) should_not raise_error(NamedError, Regexp).
-
#respond_to(sym) ⇒ Object
:call-seq: should respond_to(:sym) should_not respond_to(:sym).
-
#satisfy(&block) ⇒ Object
:call-seq: should satisfy {} should_not satisfy {}.
-
#throw_symbol(sym = nil) ⇒ Object
:call-seq: should throw_symbol() should throw_symbol(:sym) should_not throw_symbol() should_not throw_symbol(:sym).
Dynamic Method Handling
This class handles dynamic methods through the method_missing method
#method_missing(sym, *args, &block) ⇒ Object
:nodoc:
135 136 137 138 139 |
# File 'lib/spec/matchers.rb', line 135 def method_missing(sym, *args, &block) # :nodoc: return Matchers::Be.new(sym, *args) if sym.starts_with?("be_") return Matchers::Has.new(sym, *args) if sym.starts_with?("have_") super end |
Class Method Details
.generated_description=(name) ⇒ Object
130 131 132 |
# File 'lib/spec/matchers.rb', line 130 def generated_description=(name) notify_callbacks(:description_generated, name) end |
Instance Method Details
#be(*args) ⇒ Object
:call-seq:
should be_true
should be_false
should be_nil
should be_arbitrary_predicate(*args)
should_not be_nil
should_not be_arbitrary_predicate(*args)
Given true, false, or nil, will pass if actual is true, false or nil (respectively).
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.
Examples
target.should be_true
target.should be_false
target.should be_nil
target.should_not be_nil
collection.should be_empty #passes if target.empty?
"this string".should be_an_intance_of(String)
target.should_not be_empty #passes unless target.empty?
target.should_not be_old_enough(16) #passes unless target.old_enough?(16)
157 158 159 |
# File 'lib/spec/matchers/be.rb', line 157 def be(*args) Matchers::Be.new(*args) end |
#be_close(expected, delta) ⇒ Object
:call-seq:
should be_close(expected, delta)
should_not be_close(expected, delta)
Passes if actual == expected +/- delta
Example
result.should be_close(3.0, 0.5)
33 34 35 |
# File 'lib/spec/matchers/be_close.rb', line 33 def be_close(expected, delta) Matchers::BeClose.new(expected, delta) end |
#change(target = nil, message = nil, &block) ⇒ Object
:call-seq:
should change(receiver, , &block)
should change(receiver, , &block).by(value)
should change(receiver, , &block).from(old).to(new)
should_not change(receiver, , &block)
Allows you to specify that a Proc will cause some value to change.
Examples
lambda {
team.add_player(player)
}.should change(roster, :count)
lambda {
team.add_player(player)
}.should change(roster, :count).by(1)
string = "string"
lambda {
string.reverse
}.should change { string }.from("string").to("gnirts")
lambda {
person.happy_birthday
}.should change(person, :birthday).from(32).to(33)
lambda {
employee.
}.should change(employee, :title).from("Mail Clerk").to("CEO")
Evaluates receiver.message
or block
before and after it evaluates the c object (generated by the lambdas in the examples above).
Then compares the values before and after the receiver.message
and evaluates the difference compared to the expected difference.
Warning
should_not
change
only supports the form with no subsequent calls to be
, to
or from
.
blocks passed to should
change
and should_not
change
must use the {}
form (do/end
is not supported)
116 117 118 |
# File 'lib/spec/matchers/change.rb', line 116 def change(target=nil, =nil, &block) Matchers::Change.new(target, , &block) end |
#eql(expected) ⇒ Object
:call-seq:
should eql(expected)
should_not eql(expected)
Passes if actual and expected are of equal value, but not necessarily the same object.
See www.ruby-doc.org/core/classes/Object.html#M001057 for more information about equality in Ruby.
Examples
5.should eql(5)
5.should_not eql(3)
39 40 41 |
# File 'lib/spec/matchers/eql.rb', line 39 def eql(expected) Matchers::Eql.new(expected) end |
#equal(expected) ⇒ Object
:call-seq:
should equal(expected)
should_not equal(expected)
Passes if actual and expected are the same object (object identity).
See www.ruby-doc.org/core/classes/Object.html#M001057 for more information about equality in Ruby.
Examples
5.should equal(5) #Fixnums are equal
"5".should_not equal("5") #Strings that look the same are not the same object
39 40 41 |
# File 'lib/spec/matchers/equal.rb', line 39 def equal(expected) Matchers::Equal.new(expected) end |
#have(n) ⇒ Object Also known as: have_exactly
:call-seq:
should have(number).named_collection__or__sugar
should_not have(number).named_collection__or__sugar
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 an expectation about its length
Examples
# Passes if team.players.size == 11
team.should have(11).players
# Passes if [1,2,3].length == 3
[1,2,3].should have(3).items #"items" is pure sugar
# Passes if "this string".length == 11
"this string".should have(11).characters #"characters" is pure sugar
111 112 113 |
# File 'lib/spec/matchers/have.rb', line 111 def have(n) Matchers::Have.new(n) end |
#have_at_least(n) ⇒ Object
:call-seq:
should have_at_least(number).items
Exactly like have() with >=.
Warning
should_not
have_at_least
is not supported
124 125 126 |
# File 'lib/spec/matchers/have.rb', line 124 def have_at_least(n) Matchers::Have.new(n, :at_least) end |
#have_at_most(n) ⇒ Object
:call-seq:
should have_at_most(number).items
Exactly like have() with <=.
Warning
should_not
have_at_most
is not supported
136 137 138 |
# File 'lib/spec/matchers/have.rb', line 136 def have_at_most(n) Matchers::Have.new(n, :at_most) end |
#include(expected) ⇒ Object
:call-seq:
should include(expected)
should_not include(expected)
Passes if actual includes expected. This works for collections and Strings
Examples
[1,2,3].should include(3)
[1,2,3].should_not include(4)
"spread".should include("read")
"spread".should_not include("red")
46 47 48 |
# File 'lib/spec/matchers/include.rb', line 46 def include(expected) Matchers::Include.new(expected) end |
#match(regexp) ⇒ Object
:call-seq:
should match(regexp)
should_not match(regexp)
Given a Regexp, passes if actual =~ regexp
Examples
email.should match(/^([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})$/i)
37 38 39 |
# File 'lib/spec/matchers/match.rb', line 37 def match(regexp) Matchers::Match.new(regexp) end |
#raise_error(error = Exception, message = nil) ⇒ Object
:call-seq:
should raise_error()
should raise_error(NamedError)
should raise_error(NamedError, String)
should raise_error(NamedError, Regexp)
should_not raise_error()
should_not raise_error(NamedError)
should_not raise_error(NamedError, String)
should_not raise_error(NamedError, Regexp)
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.
Examples
lambda { do_something_risky }.should raise_error
lambda { do_something_risky }.should raise_error(PoorRiskDecisionError)
lambda { do_something_risky }.should raise_error(PoorRiskDecisionError, "that was too risky")
lambda { do_something_risky }.should raise_error(PoorRiskDecisionError, /oo ri/)
lambda { do_something_risky }.should_not raise_error
lambda { do_something_risky }.should_not raise_error(PoorRiskDecisionError)
lambda { do_something_risky }.should_not raise_error(PoorRiskDecisionError, "that was too risky")
lambda { do_something_risky }.should_not raise_error(PoorRiskDecisionError, /oo ri/)
96 97 98 |
# File 'lib/spec/matchers/raise_error.rb', line 96 def raise_error(error=Exception, =nil) Matchers::RaiseError.new(error, ) end |
#respond_to(sym) ⇒ Object
:call-seq:
should respond_to(:sym)
should_not respond_to(:sym)
Matches if the target object responds to :sym
31 32 33 |
# File 'lib/spec/matchers/respond_to.rb', line 31 def respond_to(sym) Matchers::RespondTo.new(sym) end |
#satisfy(&block) ⇒ Object
:call-seq:
should satisfy {}
should_not satisfy {}
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.
Examples
5.should satisfy { |n|
n > 3
}
43 44 45 |
# File 'lib/spec/matchers/satisfy.rb', line 43 def satisfy(&block) Matchers::Satisfy.new(&block) end |
#throw_symbol(sym = nil) ⇒ Object
:call-seq:
should throw_symbol()
should throw_symbol(:sym)
should_not throw_symbol()
should_not throw_symbol(:sym)
Given a Symbol argument, matches if a proc throws the specified Symbol.
Given no argument, matches if a proc throws any Symbol.
Examples
lambda { do_something_risky }.should throw_symbol
lambda { do_something_risky }.should throw_symbol(:that_was_risky)
lambda { do_something_risky }.should_not throw_symbol
lambda { do_something_risky }.should_not throw_symbol(:that_was_risky)
71 72 73 |
# File 'lib/spec/matchers/throw_symbol.rb', line 71 def throw_symbol(sym=nil) Matchers::ThrowSymbol.new(sym) end |