Module: RSpec::Matchers

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/built_in.rb,
lib/rspec/matchers/be_close.rb,
lib/rspec/matchers/built_in/be.rb,
lib/rspec/matchers/built_in/eq.rb,
lib/rspec/matchers/built_in/has.rb,
lib/rspec/matchers/built_in/eql.rb,
lib/rspec/matchers/built_in/have.rb,
lib/rspec/matchers/match_aliases.rb,
lib/rspec/matchers/built_in/cover.rb,
lib/rspec/matchers/built_in/match.rb,
lib/rspec/matchers/built_in/yield.rb,
lib/rspec/matchers/built_in/equal.rb,
lib/rspec/matchers/method_missing.rb,
lib/rspec/matchers/built_in/exist.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/expectations/configuration.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/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/differentiate_block_method_types.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)
failure_message_for_should

These methods are also part of the matcher protocol, but are optional:

does_not_match?(actual)
failure_message_for_should_not
description
supports_block_expectations?

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 "bea" and "bean_", 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 havekey(:key) and RSpec will call haskey?(: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 beinzone 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

  failure_message_for_should do |player|
    # generate and return the appropriate string.
  end

  failure_message_for_should_not 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 (failuremessageforshould and failuremessageforshouldnot) are passed the actual value (the receiver of expect(..) or expect(..).notto).

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 failure_message_for_should
    "expected #{@target.inspect} to be in Zone #{@expected}"
  end

  def failure_message_for_should_not
    "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, MatchAliases, Pretty Classes: DifferentiateBlockMethodTypes

Class Attribute Summary (collapse)

Class Method Summary (collapse)

Instance Method Summary (collapse)

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

- (Object) method_missing(method, *args) (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

+ (RSpec::Expectations::Configuration) configuration

The configuration object

Returns:



102
103
104
# File 'lib/rspec/expectations/configuration.rb', line 102

def self.configuration
  @configuration ||= Expectations::Configuration.new
end

+ (Object) const_missing(name)



714
715
716
717
718
719
720
721
722
723
724
725
726
# File 'lib/rspec/matchers.rb', line 714

def self.const_missing(name)
  case name
    when :OperatorMatcher
      RSpec.deprecate("`RSpec::Matchers::OperatorMatcher`",
                      :replacement => "`RSpec::Matchers::BuiltIn::OperatorMatcher`")
      BuiltIn::OperatorMatcher
    when :Configuration
      RSpec.deprecate("`RSpec::Matchers::Configuration`",
                      :replacement => "`RSpec::Expectations::Configuration`")
      Expectations::Configuration
    else super
  end
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

+ (Boolean) is_a_matcher?(obj)

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.

Returns:

  • (Boolean)


180
181
182
183
184
185
186
# File 'lib/rspec/matchers.rb', line 180

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

- (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 "bean" (e.g. beaninstanceof), "bea" (e.g. beakindof) or "be" (e.g. be_empty), letting you choose the prefix that best suits the predicate.

Examples:

expect(actual).to     be_truthy
expect(actual).to     be_falsey
expect(actual).to     be_nil
expect(actual).to     be_[arbitrary_predicate](*args)
expect(actual).not_to be_nil
expect(actual).not_to be_[arbitrary_predicate](*args)


241
242
243
244
# File 'lib/rspec/matchers.rb', line 241

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)



247
248
249
# File 'lib/rspec/matchers.rb', line 247

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)

Examples:

expect(5).to     be_a_kind_of(Fixnum)
expect(5).to     be_a_kind_of(Numeric)
expect(5).not_to be_a_kind_of(Float)


273
274
275
# File 'lib/rspec/matchers.rb', line 273

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)

Examples:

expect(5).to     be_an_instance_of(Fixnum)
expect(5).not_to be_an_instance_of(Numeric)
expect(5).not_to be_an_instance_of(Float)


260
261
262
# File 'lib/rspec/matchers.rb', line 260

def be_an_instance_of(expected)
  BuiltIn::BeAnInstanceOf.new(expected)
end

- (Object) be_close(expected, delta)

Deprecated.

use +be_within+ instead.



4
5
6
7
8
9
10
# 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})",
    :type        => 'the be_close matcher'
  )
  be_within(delta).of(expected)
end

- (Object) be_false



196
197
198
199
200
201
202
# File 'lib/rspec/matchers.rb', line 196

def be_false
  RSpec.deprecate("`be_false`", :replacement =>
    "`be_falsey` (for Ruby's conditional semantics) or " +
    "`be false` (for exact `== false` equality)"
  )
  BuiltIn::BeFalsey.new
end

- (Object) be_falsey Also known as: be_falsy

Passes if actual is falsy (false or nil)



210
211
212
# File 'lib/rspec/matchers.rb', line 210

def be_falsey
  BuiltIn::BeFalsey.new
end

- (Object) be_nil

Passes if actual is nil



217
218
219
# File 'lib/rspec/matchers.rb', line 217

def be_nil
  BuiltIn::BeNil.new
end

- (Object) be_true



188
189
190
191
192
193
194
# File 'lib/rspec/matchers.rb', line 188

def be_true
  RSpec.deprecate("`be_true`", :replacement =>
    "`be_truthy` (for Ruby's conditional semantics) or " +
    "`be true` (for exact `== true` equality)"
  )
  BuiltIn::BeTruthy.new
end

- (Object) be_truthy

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



205
206
207
# File 'lib/rspec/matchers.rb', line 205

def be_truthy
  BuiltIn::BeTruthy.new
end

- (Object) be_within(delta)

Passes if actual == expected +/- delta

Examples:

expect(result).to     be_within(0.5).of(3.0)
expect(result).not_to be_within(0.5).of(3.0)


285
286
287
# File 'lib/rspec/matchers.rb', line 285

def be_within(delta)
  BuiltIn::BeWithin.new(delta)
end

- (Object) change(receiver = nil, message = nil)

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( ... ).notto change only supports the form with no subsequent calls to by, byatleast, byat_most, to or from.

Examples:

expect {
  team.add_player(player)
}.to change(roster, :count)

expect {
  team.add_player(player)
}.to change(roster, :count).by(1)

expect {
  team.add_player(player)
}.to change(roster, :count).by_at_least(1)

expect {
  team.add_player(player)
}.to change(roster, :count).by_at_most(1)

string = "string"
expect {
  string.reverse!
}.to change { string }.from("string").to("gnirts")

string = "string"
expect {
  string
}.not_to change { string }

expect {
  person.happy_birthday
}.to change(person, :birthday).from(32).to(33)

expect {
  employee.develop_great_new_social_networking_app
}.to change(employee, :title).from("Mail Clerk").to("CEO")

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

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

Parameters:

  • receiver (Object) (defaults to: nil)
  • message (Symbol) (defaults to: nil)

    the message to send the receiver



355
356
357
# File 'lib/rspec/matchers.rb', line 355

def change(receiver=nil, message=nil, &block)
  BuiltIn::Change.new(receiver, message, &block)
end

- (Object) cover(*values)



371
372
373
# File 'lib/rspec/matchers.rb', line 371

def cover(*values)
  BuiltIn::Cover.new(*values)
end

- (Object) end_with(*expected)

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.

Examples:

expect("this string").to   end_with "string"
expect([0, 1, 2, 3, 4]).to end_with 4
expect([0, 2, 3, 4, 4]).to end_with 3, 4


385
386
387
# File 'lib/rspec/matchers.rb', line 385

def end_with(*expected)
  BuiltIn::EndWith.new(*expected)
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.

Examples:

expect(5).to     eq(5)
expect(5).not_to eq(3)


398
399
400
# File 'lib/rspec/matchers.rb', line 398

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.

Examples:

expect(5).to     eql(5)
expect(5).not_to eql(3)


411
412
413
# File 'lib/rspec/matchers.rb', line 411

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.

Examples:

expect(5).to       equal(5)   # Fixnums are equal
expect("5").not_to equal("5") # Strings that look the same are not the same object


424
425
426
# File 'lib/rspec/matchers.rb', line 424

def equal(expected)
  BuiltIn::Equal.new(expected)
end

- (Object) exist(*args)

Passes if actual.exist? or actual.exists?

Examples:

expect(File).to exist("path/to/file")


432
433
434
# File 'lib/rspec/matchers.rb', line 432

def exist(*args)
  BuiltIn::Exist.new(*args)
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.

Examples:

# Passes if team.players.size == 11
expect(team).to have(11).players

# Passes if [1,2,3].length == 3
expect([1,2,3]).to have(3).items #"items" is pure sugar

# Passes if ['a', 'b', 'c'].count == 3
expect([1,2,3]).to have(3).items #"items" is pure sugar

# Passes if "this string".length == 11
expect("this string").to have(11).characters #"characters" is pure sugar


464
465
466
# File 'lib/rspec/matchers.rb', line 464

def have(n)
  BuiltIn::Have.new(n)
end

- (Object) have_at_least(n)

Exactly like have() with >=.

Warning:

expect(..).not_to have_at_least is not supported

Examples:

expect("this").to have_at_least(3).letters


477
478
479
# File 'lib/rspec/matchers.rb', line 477

def have_at_least(n)
  BuiltIn::Have.new(n, :at_least)
end

- (Object) have_at_most(n)

Exactly like have() with <=.

Warning:

expect(..).not_to have_at_most is not supported

Examples:

expect("this").to have_at_most(4).letters


489
490
491
# File 'lib/rspec/matchers.rb', line 489

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.

Examples:

expect([1,2,3]).to      include(3)
expect([1,2,3]).to      include(2,3)
expect([1,2,3]).to      include(2,3,4) # fails
expect([1,2,3]).not_to  include(4)
expect("spread").to     include("read")
expect("spread").not_to include("red")


505
506
507
# File 'lib/rspec/matchers.rb', line 505

def include(*expected)
  BuiltIn::Include.new(*expected)
end

- (Object) match(expected) Also known as: match_regex

Note:

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.

Examples:

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


523
524
525
# File 'lib/rspec/matchers.rb', line 523

def match(expected)
  BuiltIn::Match.new(expected)
end

- (Object) match_array(array)

Note:

This is also available using the =~ operator with should, but =~ is not supported with expect.

Note:

This matcher only supports positive expectations. expect(..).notto matcharray(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.

Examples:

expect([1,2,3]).to match_array([1,2,3])
expect([1,2,3]).to match_array([1,3,2])


708
709
710
# File 'lib/rspec/matchers.rb', line 708

def match_array(array)
  BuiltIn::MatchArray.new(array)
end

- (Object) raise_error(error = Exception, message = nil) 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

Examples:

expect { do_something_risky }.to raise_error
expect { do_something_risky }.to raise_error(PoorRiskDecisionError)
expect { do_something_risky }.to raise_error(PoorRiskDecisionError) { |error| expect(error.data).to eq 42 }
expect { do_something_risky }.to raise_error(PoorRiskDecisionError, "that was too risky")
expect { do_something_risky }.to raise_error(PoorRiskDecisionError, /oo ri/)

expect { do_something_risky }.not_to raise_error


544
545
546
# File 'lib/rspec/matchers.rb', line 544

def raise_error(error=Exception, message=nil, &block)
  BuiltIn::RaiseError.new(error, message, &block)
end

- (Object) respond_to(*names)

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

expect("string").to respond_to(:length)



557
558
559
# File 'lib/rspec/matchers.rb', line 557

def respond_to(*names)
  BuiltIn::RespondTo.new(*names)
end

- (Object) 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:

expect(5).to satisfy { |n| n > 3 }


574
575
576
# File 'lib/rspec/matchers.rb', line 574

def satisfy(&block)
  BuiltIn::Satisfy.new(&block)
end

- (Object) start_with(*expected)

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.

Examples:

expect("this string").to   start_with "this s"
expect([0, 1, 2, 3, 4]).to start_with 0
expect([0, 2, 3, 4, 4]).to start_with 0, 1


588
589
590
# File 'lib/rspec/matchers.rb', line 588

def start_with(*expected)
  BuiltIn::StartWith.new(*expected)
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.

Examples:

expect { do_something_risky }.to throw_symbol
expect { do_something_risky }.to throw_symbol(:that_was_risky)
expect { do_something_risky }.to throw_symbol(:that_was_risky, 'culprit')

expect { do_something_risky }.not_to throw_symbol
expect { do_something_risky }.not_to throw_symbol(:that_was_risky)
expect { do_something_risky }.not_to throw_symbol(:that_was_risky, 'culprit')


608
609
610
# File 'lib/rspec/matchers.rb', line 608

def throw_symbol(expected_symbol=nil, expected_arg=nil)
  BuiltIn::ThrowSymbol.new(expected_symbol, expected_arg)
end

- (Object) 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.

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

Examples:

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


624
625
626
# File 'lib/rspec/matchers.rb', line 624

def yield_control
  BuiltIn::YieldControl.new
end

- (Object) yield_successive_args(*args)

Note:

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.

Examples:

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)


690
691
692
# File 'lib/rspec/matchers.rb', line 690

def yield_successive_args(*args)
  BuiltIn::YieldSuccessiveArgs.new(*args)
end

- (Object) yield_with_args(*args)

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.

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.

Examples:

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)


670
671
672
# File 'lib/rspec/matchers.rb', line 670

def yield_with_args(*args)
  BuiltIn::YieldWithArgs.new(*args)
end

- (Object) yield_with_no_args

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.

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

Examples:

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


641
642
643
# File 'lib/rspec/matchers.rb', line 641

def yield_with_no_args
  BuiltIn::YieldWithNoArgs.new
end