module RSpec::Matchers

Attributes

last_matcher[RW]
last_should[RW]

Public Class Methods

clear_generated_description() click to toggle source
# File lib/rspec/matchers/generated_descriptions.rb, line 7
def self.clear_generated_description
  self.last_matcher = nil
  self.last_should = nil
end
configuration() click to toggle source

The configuration object @return [RSpec::Matchers::Configuration] the configuration object

# File lib/rspec/matchers/configuration.rb, line 100
def self.configuration
  @configuration ||= Configuration.new
end
generated_description() click to toggle source
# 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

Private Class Methods

last_description() click to toggle source
# File lib/rspec/matchers/generated_descriptions.rb, line 19
    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 { object.should matcher }

or this:

it { should 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

Public Instance Methods

be(*args) click to toggle source

@example

actual.should be_true
actual.should be_false
actual.should be_nil
actual.should be_[arbitrary_predicate](*args)
actual.should_not be_nil
actual.should_not be_[arbitrary_predicate](*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 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.

# File lib/rspec/matchers.rb, line 227
def be(*args)
  args.empty? ?
    Matchers::BuiltIn::Be.new : equal(*args)
end
be_a(klass) click to toggle source

passes if target.kind_of?(klass)

# File lib/rspec/matchers.rb, line 233
def be_a(klass)
  be_a_kind_of(klass)
end
Also aliased as: be_an
be_a_kind_of(expected) click to toggle source

Passes if actual.kind_of?(expected)

@example

5.should be_kind_of(Fixnum)
5.should be_kind_of(Numeric)
5.should_not be_kind_of(Float)
# File lib/rspec/matchers.rb, line 259
def be_a_kind_of(expected)
  BuiltIn::BeAKindOf.new(expected)
end
Also aliased as: be_kind_of
be_an(klass)
Alias for: be_a
be_an_instance_of(expected) click to toggle source

Passes if actual.instance_of?(expected)

@example

5.should be_instance_of(Fixnum)
5.should_not be_instance_of(Numeric)
5.should_not be_instance_of(Float)
# File lib/rspec/matchers.rb, line 246
def be_an_instance_of(expected)
  BuiltIn::BeAnInstanceOf.new(expected)
end
Also aliased as: be_instance_of
be_close(expected, delta) click to toggle source

@deprecated use be_within instead.

# 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
be_false() click to toggle source

Passes if actual is falsy (false or nil)

# File lib/rspec/matchers.rb, line 198
def be_false
  BuiltIn::BeFalse.new
end
be_instance_of(expected)
Alias for: be_an_instance_of
be_kind_of(expected)
Alias for: be_a_kind_of
be_nil() click to toggle source

Passes if actual is nil

# File lib/rspec/matchers.rb, line 203
def be_nil
  BuiltIn::BeNil.new
end
be_true() click to toggle source

Passes if actual is truthy (anything but false or nil)

# File lib/rspec/matchers.rb, line 193
def be_true
  BuiltIn::BeTrue.new
end
be_within(delta) click to toggle source

Passes if actual == expected +/- delta

@example

result.should be_within(0.5).of(3.0)
result.should_not be_within(0.5).of(3.0)
# File lib/rspec/matchers.rb, line 271
def be_within(delta)
  BuiltIn::BeWithin.new(delta)
end
change(receiver=nil, message=nil, &block) click to toggle source

Applied to a proc, specifies that its execution will cause some value to change.

@param [Object] receiver @param [Symbol] message the message to send the receiver

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.

@example

lambda {
  team.add_player(player)
}.should change(roster, :count)

lambda {
  team.add_player(player)
}.should change(roster, :count).by(1)

lambda {
  team.add_player(player)
}.should change(roster, :count).by_at_least(1)

lambda {
  team.add_player(player)
}.should change(roster, :count).by_at_most(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.develop_great_new_social_networking_app
}.should change(employee, :title).from("Mail Clerk").to("CEO")

lambda {
  doctor.leave_office
}.should change(doctor, :sign).from(/is in/).to(/is out/)

user = User.new(:type => "admin")
lambda {
  user.symbolize_type
}.should change(user, :type).from(String).to(Symbol)

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.

# File lib/rspec/matchers.rb, line 337
def change(receiver=nil, message=nil, &block)
  BuiltIn::Change.new(receiver, message, &block)
end
cover(*values) click to toggle source

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.

@example

(1..10).should cover(5)
(1..10).should cover(4, 6)
(1..10).should cover(4, 6, 11) # will fail
(1..10).should_not cover(11)
(1..10).should_not cover(5)    # will fail
### Warning

Ruby >= 1.9 only

# File lib/rspec/matchers.rb, line 353
def cover(*values)
  BuiltIn::Cover.new(*values)
end
end_with(*expected) click to toggle source

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.

@example

"this string".should end_with "string"
[0, 1, 2, 3, 4].should end_with 4
[0, 2, 3, 4, 4].should end_with 3, 4
# File lib/rspec/matchers.rb, line 367
def end_with(*expected)
  BuiltIn::EndWith.new(*expected)
end
eq(expected) click to toggle source

Passes if actual == expected.

See www.ruby-doc.org/core/classes/Object.html#M001057 for more information about equality in Ruby.

@example

5.should eq(5)
5.should_not eq(3)
# File lib/rspec/matchers.rb, line 379
def eq(expected)
  BuiltIn::Eq.new(expected)
end
eql(expected) click to toggle source

Passes if +actual.eql?(expected)+

See www.ruby-doc.org/core/classes/Object.html#M001057 for more information about equality in Ruby.

@example

5.should eql(5)
5.should_not eql(3)
# File lib/rspec/matchers.rb, line 391
def eql(expected)
  BuiltIn::Eql.new(expected)
end
equal(expected) click to toggle source

Passes if actual.equal?(expected) (object identity).

See www.ruby-doc.org/core/classes/Object.html#M001057 for more information about equality in Ruby.

@example

5.should equal(5) # Fixnums are equal
"5".should_not equal("5") # Strings that look the same are not the same object
# File lib/rspec/matchers.rb, line 403
def equal(expected)
  BuiltIn::Equal.new(expected)
end
exist(*args) click to toggle source

Passes if `actual.exist?` or `actual.exists?`

@example

File.should exist("path/to/file")
# File lib/rspec/matchers.rb, line 411
def exist(*args)
  BuiltIn::Exist.new(*args)
end
have(n) click to toggle source

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.

@example

# 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 ['a', 'b', 'c'].count == 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
# File lib/rspec/matchers.rb, line 443
def have(n)
  BuiltIn::Have.new(n)
end
Also aliased as: have_exactly
have_at_least(n) click to toggle source

Exactly like have() with >=.

@example

"this".should have_at_least(3).letters

### Warning:

`should_not #have_at_least` is not supported

# File lib/rspec/matchers.rb, line 456
def have_at_least(n)
  BuiltIn::Have.new(n, :at_least)
end
have_at_most(n) click to toggle source

Exactly like have() with <=.

@example

should have_at_most(number).items

### Warning:

`should_not #have_at_most` is not supported

# File lib/rspec/matchers.rb, line 468
def have_at_most(n)
  BuiltIn::Have.new(n, :at_most)
end
have_exactly(n)
Alias for: have
include(*expected) click to toggle source

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.

@example

[1,2,3].should include(3)
[1,2,3].should include(2,3) #would pass
[1,2,3].should include(2,3,4) #would fail
[1,2,3].should_not include(4)
"spread".should include("read")
"spread".should_not include("red")
# File lib/rspec/matchers.rb, line 484
def include(*expected)
  BuiltIn::Include.new(*expected)
end
match(expected) click to toggle source

Given a Regexp or String, passes if actual.match(pattern)

@example

email.should match(/^([^\s]+)((?:[-a-z0-9]+\.)+[a-z]{2,})$/i)
email.should match("@example.com")
zipcode.should match_regex(/\A\d{5}(-\d{4})?\z/)
zipcode.should match_regex("90210")

@note Due to Ruby's method dispatch mechanism, using the `#match` matcher 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.

# File lib/rspec/matchers.rb, line 502
def match(expected)
  BuiltIn::Match.new(expected)
end
Also aliased as: match_regex
match_array(array) click to toggle source

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 This is also available using the `=~` operator with `should`,

but `=~` is not supported with `expect`.

@note There is no should_not version of array.should =~ other_array

@example

expect([1,2,3]).to match_array([1,2,3])
expect([1,2,3]).to match_array([1,3,2])
[1,2,3].should   =~ [1,2,3]   # => would pass
[1,2,3].should   =~ [2,3,1]   # => would pass
[1,2,3,4].should =~ [1,2,3]   # => would fail
[1,2,2,3].should =~ [1,2,3]   # => would fail
[1,2,3].should   =~ [1,2,3,4] # => would fail
# File lib/rspec/matchers.rb, line 693
def match_array(array)
  BuiltIn::MatchArray.new(array)
end
match_regex(expected)
Alias for: match
raise_error(error=Exception, message=nil, &block) click to toggle source

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

@example

lambda { do_something_risky }.should raise_error
lambda { do_something_risky }.should raise_error(PoorRiskDecisionError)
lambda { do_something_risky }.should raise_error(PoorRiskDecisionError) { |error| error.data.should == 42 }
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/)
# File lib/rspec/matchers.rb, line 526
def raise_error(error=Exception, message=nil, &block)
  BuiltIn::RaiseError.new(error, message, &block)
end
Also aliased as: raise_exception
raise_exception(error=Exception, message=nil, &block)
Alias for: raise_error
respond_to(*names) click to toggle source

Matches if the target object responds to all of the names provided. Names can be Strings or Symbols.

@example

# File lib/rspec/matchers.rb, line 537
def respond_to(*names)
  BuiltIn::RespondTo.new(*names)
end
satisfy(&block) click to toggle source

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.

@example

5.should satisfy { |n|
  n > 3
}
# File lib/rspec/matchers.rb, line 556
def satisfy(&block)
  BuiltIn::Satisfy.new(&block)
end
start_with(*expected) click to toggle source

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.

@example

"this string".should start_with "this s"
[0, 1, 2, 3, 4].should start_with 0
[0, 2, 3, 4, 4].should start_with 0, 1
# File lib/rspec/matchers.rb, line 570
def start_with(*expected)
  BuiltIn::StartWith.new(*expected)
end
throw_symbol(expected_symbol=nil, expected_arg=nil) click to toggle source

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.

@example

lambda { do_something_risky }.should throw_symbol
lambda { do_something_risky }.should throw_symbol(:that_was_risky)
lambda { do_something_risky }.should throw_symbol(:that_was_risky, culprit)

lambda { do_something_risky }.should_not throw_symbol
lambda { do_something_risky }.should_not throw_symbol(:that_was_risky)
lambda { do_something_risky }.should_not throw_symbol(:that_was_risky, culprit)
# File lib/rspec/matchers.rb, line 590
def throw_symbol(expected_symbol=nil, expected_arg=nil)
  BuiltIn::ThrowSymbol.new(expected_symbol, expected_arg)
end
yield_control() click to toggle source

Passes if the method called in the expect block yields, regardless of whether or not arguments are yielded.

@example

expect { |b| 5.tap(&b) }.to yield_control
expect { |b| "a".to_sym(&b) }.not_to yield_control

@note Your expect block must accept a parameter and pass it on to

the method-under-test as a block.

@note This matcher is not designed for use with methods that yield

multiple times.
# File lib/rspec/matchers.rb, line 606
def yield_control
  BuiltIn::YieldControl.new
end
yield_successive_args(*args) click to toggle source

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.

@example

expect { |b| [1, 2, 3].each(&b) }.to yield_successive_args(1, 2, 3)
expect { |b| { :a => 1, :b => 2 }.each(&b) }.to yield_successive_args([:a, 1], [:b, 2])
expect { |b| [1, 2, 3].each(&b) }.not_to yield_successive_args(1, 2)

@note Your expect block must accept a parameter and pass it on to

the method-under-test as a block.
# File lib/rspec/matchers.rb, line 672
def yield_successive_args(*args)
  BuiltIn::YieldSuccessiveArgs.new(*args)
end
yield_with_args(*args) click to toggle source

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.

@example

expect { |b| 5.tap(&b) }.to yield_with_args # because #tap yields an arg
expect { |b| 5.tap(&b) }.to yield_with_args(5) # because 5 == 5
expect { |b| 5.tap(&b) }.to yield_with_args(Fixnum) # because Fixnum === 5
expect { |b| File.open("f.txt", &b) }.to yield_with_args(/txt/) # because /txt/ === "f.txt"

expect { |b| User.transaction(&b) }.not_to yield_with_args # because it yields no args
expect { |b| 5.tap(&b) }.not_to yield_with_args(1, 2, 3)

@note Your expect block must accept a parameter and pass it on to

the method-under-test as a block.

@note This matcher is not designed for use with methods that yield

multiple times.
# File lib/rspec/matchers.rb, line 652
def yield_with_args(*args)
  BuiltIn::YieldWithArgs.new(*args)
end
yield_with_no_args() click to toggle source

Passes if the method called in the expect block yields with no arguments. Fails if it does not yield, or yields with arguments.

@example

expect { |b| User.transaction(&b) }.to yield_with_no_args
expect { |b| 5.tap(&b) }.not_to yield_with_no_args # because it yields with `5`
expect { |b| "a".to_sym(&b) }.not_to yield_with_no_args # because it does not yield

@note Your expect block must accept a parameter and pass it on to

the method-under-test as a block.

@note This matcher is not designed for use with methods that yield

multiple times.
# File lib/rspec/matchers.rb, line 623
def yield_with_no_args
  BuiltIn::YieldWithNoArgs.new
end

Private Instance Methods

method_missing(method, *args, &block) click to toggle source
Calls superclass method
# 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