Module: RSpec::Mocks::ExampleMethods

Includes:
ArgumentMatchers
Defined in:
lib/rspec/mocks/example_methods.rb

Overview

Contains methods intended to be used from within code examples. Mix this in to your test context (such as a test framework base class) to use rspec-mocks with your test framework. If you're using rspec-core, it'll take care of doing this for you.

Defined Under Namespace

Modules: ExpectHost

Instance Method Summary (collapse)

Methods included from ArgumentMatchers

#any_args, #anything, #array_including, #boolean, #duck_type, #hash_excluding, #hash_including, #instance_of, #kind_of, #no_args

Instance Method Details

- (Object) allow

Note:

If you disable the :expect syntax this method will be undefined.

Used to wrap an object in preparation for stubbing a method on it.

Examples:


allow(dbl).to receive(:foo).with(5).and_return(:return_value)

    
# File 'lib/rspec/mocks/example_methods.rb', line 188

- (Object) allow_any_instance_of

Note:

This is only available when you have enabled the expect syntax.

Used to wrap a class in preparation for stubbing a method on instances of it.

Examples:


allow_any_instance_of(MyClass).to receive(:foo)

    
# File 'lib/rspec/mocks/example_methods.rb', line 208

- (Object) allow_message_expectations_on_nil

Disables warning messages about expectations being set on nil.

By default warning messages are issued when expectations are set on nil. This is to prevent false-positives and to catch potential bugs early on.

92
93
94
# File 'lib/rspec/mocks/example_methods.rb', line 92
def allow_message_expectations_on_nil
  RSpec::Mocks.space.proxy_for(nil).warn_about_expectations = false
end

- (Object) class_double(doubled_class) - (Object) class_double(doubled_class, stubs)

Constructs a test double against a specific class. If the given class name has been loaded, only class methods defined on the class are allowed to be stubbed. In all other ways it behaves like a double.

Overloads:

  • - (Object) class_double(doubled_class)

    Parameters:

    • doubled_class (String, Module)
  • - (Object) class_double(doubled_class, stubs)

    Parameters:

    • doubled_class (String, Module)
    • stubs (Hash)

      hash of message/return-value pairs

Returns:

  • ClassVerifyingDouble

66
67
68
69
# File 'lib/rspec/mocks/example_methods.rb', line 66
def class_double(doubled_class, *args)
  ref = ObjectReference.for(doubled_class)
  ExampleMethods.declare_verifying_double(ClassVerifyingDouble, ref, *args)
end

- (Double) double - (Double) double(name) - (Double) double(stubs) - (Double) double(name, stubs)

Constructs an instance of RSpec::Mocks::Double configured with an optional name, used for reporting in failure messages, and an optional hash of message/return-value pairs.

Examples:


book = double("book", :title => "The RSpec Book")
book.title #=> "The RSpec Book"

card = double("card", :suit => "Spades", :rank => "A")
card.suit  #=> "Spades"
card.rank  #=> "A"

Overloads:

  • - (Double) double(name)

    Parameters:

    • name (String/Symbol)

      used to clarify intent

  • - (Double) double(stubs)

    Parameters:

    • stubs (Hash)

      hash of message/return-value pairs

  • - (Double) double(name, stubs)

    Parameters:

    • name (String/Symbol)

      used to clarify intent

    • stubs (Hash)

      hash of message/return-value pairs

Returns:

35
36
37
# File 'lib/rspec/mocks/example_methods.rb', line 35
def double(*args)
  ExampleMethods.declare_double(Double, *args)
end

- (Object) expect

Note:

This method is usually provided by rspec-expectations. However, if you use rspec-mocks without rspec-expectations, there's a definition of it that is made available here. If you disable the :expect syntax this method will be undefined.

Used to wrap an object in preparation for setting a mock expectation on it.

Examples:


expect(obj).to receive(:foo).with(5).and_return(:return_value)

    
# File 'lib/rspec/mocks/example_methods.rb', line 175

- (Object) expect_any_instance_of

Note:

If you disable the :expect syntax this method will be undefined.

Used to wrap a class in preparation for setting a mock expectation on instances of it.

Examples:


expect_any_instance_of(MyClass).to receive(:foo)

    
# File 'lib/rspec/mocks/example_methods.rb', line 198

- (Object) have_received(method_name, &block)

Verifies that the given object received the expected message during the course of the test. The method must have previously been stubbed in order for messages to be verified.

Stubbing and verifying messages received in this way implements the Test Spy pattern.

Examples:


invitation = double('invitation', accept: true)
user.accept_invitation(invitation)
expect(invitation).to have_received(:accept)
# You can also use most message expectations:
expect(invitation).to have_received(:accept).with(mailer).once

Parameters:

  • method_name (Symbol)

    name of the method expected to have been called.

171
172
173
# File 'lib/rspec/mocks/example_methods.rb', line 171
def have_received(method_name, &block)
  Matchers::HaveReceived.new(method_name, &block)
end

- (Object) hide_const(constant_name)

Hides the named constant with the given value. The constant will be undefined for the duration of the test.

Like method stubs, the constant will be restored to its original value when the example completes.

Examples:


hide_const("MyClass") # => MyClass is now an undefined constant

Parameters:

  • constant_name (String)

    The fully qualified name of the constant. The current constant scoping at the point of call is not considered.

149
150
151
# File 'lib/rspec/mocks/example_methods.rb', line 149
def hide_const(constant_name)
  ConstantMutator.hide(constant_name)
end

- (Object) instance_double(doubled_class) - (Object) instance_double(doubled_class, stubs)

Constructs a test double against a specific class. If the given class name has been loaded, only instance methods defined on the class are allowed to be stubbed. In all other ways it behaves like a double.

Overloads:

  • - (Object) instance_double(doubled_class)

    Parameters:

    • doubled_class (String, Class)
  • - (Object) instance_double(doubled_class, stubs)

    Parameters:

    • doubled_class (String, Class)
    • stubs (Hash)

      hash of message/return-value pairs

Returns:

  • InstanceVerifyingDouble

50
51
52
53
# File 'lib/rspec/mocks/example_methods.rb', line 50
def instance_double(doubled_class, *args)
  ref = ObjectReference.for(doubled_class)
  ExampleMethods.declare_verifying_double(InstanceVerifyingDouble, ref, *args)
end

- (Object) object_double(object_or_name) - (Object) object_double(object_or_name, stubs)

Constructs a test double against a specific object. Only the methods the object responds to are allowed to be stubbed. If a String argument is provided, it is assumed to reference a constant object which is used for verification. In all other ways it behaves like a double.

Overloads:

  • - (Object) object_double(object_or_name)

    Parameters:

    • object_or_name (String, Object)
  • - (Object) object_double(object_or_name, stubs)

    Parameters:

    • object_or_name (String, Object)
    • stubs (Hash)

      hash of message/return-value pairs

Returns:

  • ObjectVerifyingDouble

82
83
84
85
# File 'lib/rspec/mocks/example_methods.rb', line 82
def object_double(object_or_name, *args)
  ref = ObjectReference.for(object_or_name, :allow_direct_object_refs)
  ExampleMethods.declare_verifying_double(ObjectVerifyingDouble, ref, *args)
end

- (Object) receive

Note:

If you disable the :expect syntax this method will be undefined.

Used to specify a message that you expect or allow an object to receive. The object returned by receive supports the same fluent interface that should_receive and stub have always supported, allowing you to constrain the arguments or number of times, and configure how the object should respond to the message.

Examples:


expect(obj).to receive(:hello).with("world").exactly(3).times

    
# File 'lib/rspec/mocks/example_methods.rb', line 218

- (Object) receive_message_chain(method1, method2) - (Object) receive_message_chain("method1.method2") - (Object) receive_message_chain(method1, method_to_value_hash)

Note:

If you disable the :expect syntax this method will be undefined.

stubs/mocks a chain of messages on an object or test double.

Warning:

Chains can be arbitrarily long, which makes it quite painless to violate the Law of Demeter in violent ways, so you should consider any use of receive_message_chain a code smell. Even though not all code smells indicate real problems (think fluent interfaces), receive_message_chain still results in brittle examples. For example, if you write allow(foo).to receive_message_chain(:bar, :baz => 37) in a spec and then the implementation calls foo.baz.bar, the stub will not work.

Examples:


allow(double).to receive_message_chain("foo.bar") { :baz }
allow(double).to receive_message_chain(:foo, :bar => :baz)
allow(double).to receive_message_chain(:foo, :bar) { :baz }
# Given any of ^^ these three forms ^^:
double.foo.bar # => :baz

# Common use in Rails/ActiveRecord:
allow(Article).to receive_message_chain("recent.published") { [Article.new] }

    
# File 'lib/rspec/mocks/example_methods.rb', line 245

- (Object) receive_messages

Note:

If you disable the :expect syntax this method will be undefined.

Shorthand syntax used to setup message(s), and their return value(s), that you expect or allow an object to receive. The method takes a hash of messages and their respective return values. Unlike with receive, you cannot apply further customizations using a block or the fluent interface.

Examples:


allow(obj).to receive_messages(:speak => "Hello World")
allow(obj).to receive_messages(:speak => "Hello", :meow => "Meow")

    
# File 'lib/rspec/mocks/example_methods.rb', line 231

- (Object) stub_const(constant_name, value, options = {})

Stubs the named constant with the given value. Like method stubs, the constant will be restored to its original value (or lack of one, if it was undefined) when the example completes.

Examples:


stub_const("MyClass", Class.new) # => Replaces (or defines) MyClass with a new class object.
stub_const("SomeModel::PER_PAGE", 5) # => Sets SomeModel::PER_PAGE to 5.

class CardDeck
  SUITS = [:Spades, :Diamonds, :Clubs, :Hearts]
  NUM_CARDS = 52
end
stub_const("CardDeck", Class.new)
CardDeck::SUITS # => uninitialized constant error
CardDeck::NUM_CARDS # => uninitialized constant error

stub_const("CardDeck", Class.new, :transfer_nested_constants => true)
CardDeck::SUITS # => our suits array
CardDeck::NUM_CARDS # => 52

stub_const("CardDeck", Class.new, :transfer_nested_constants => [:SUITS])
CardDeck::SUITS # => our suits array
CardDeck::NUM_CARDS # => uninitialized constant error

Parameters:

  • constant_name (String)

    The fully qualified name of the constant. The current constant scoping at the point of call is not considered.

  • value (Object)

    The value to make the constant refer to. When the example completes, the constant will be restored to its prior state.

  • options (Hash) (defaults to: {})

    Stubbing options.

Options Hash (options):

  • :transfer_nested_constants (Boolean, Array<Symbol>)

    Determines what nested constants, if any, will be transferred from the original value of the constant to the new value of the constant. This only works if both the original and new values are modules (or classes).

Returns:

  • (Object)

    the stubbed value of the constant

133
134
135
# File 'lib/rspec/mocks/example_methods.rb', line 133
def stub_const(constant_name, value, options = {})
  ConstantMutator.stub(constant_name, value, options)
end