Module: RSpec::Mocks

Defined in:
lib/rspec/mocks.rb,
lib/rspec/mocks/mock.rb,
lib/rspec/mocks/space.rb,
lib/rspec/mocks/proxy.rb,
lib/rspec/mocks/syntax.rb,
lib/rspec/mocks/errors.rb,
lib/rspec/mocks/version.rb,
lib/rspec/mocks/targets.rb,
lib/rspec/mocks/stub_chain.rb,
lib/rspec/mocks/deprecation.rb,
lib/rspec/mocks/test_double.rb,
lib/rspec/mocks/order_group.rb,
lib/rspec/mocks/mutate_const.rb,
lib/rspec/mocks/method_double.rb,
lib/rspec/mocks/proxy_for_nil.rb,
lib/rspec/mocks/configuration.rb,
lib/rspec/mocks/error_generator.rb,
lib/rspec/mocks/example_methods.rb,
lib/rspec/mocks/matchers/receive.rb,
lib/rspec/mocks/argument_matchers.rb,
lib/rspec/mocks/any_instance/chain.rb,
lib/rspec/mocks/message_expectation.rb,
lib/rspec/mocks/any_instance/recorder.rb,
lib/rspec/mocks/argument_list_matcher.rb,
lib/rspec/mocks/matchers/have_received.rb,
lib/rspec/mocks/any_instance/stub_chain.rb,
lib/rspec/mocks/instance_method_stasher.rb,
lib/rspec/mocks/extensions/instance_exec.rb,
lib/rspec/mocks/any_instance/message_chains.rb,
lib/rspec/mocks/any_instance/stub_chain_chain.rb,
lib/rspec/mocks/any_instance/expectation_chain.rb

Defined Under Namespace

Modules: AnyInstance, ArgumentMatchers, Deprecation, ExampleMethods, Matchers, RecursiveConstMethods, Syntax, TestDouble, Version Classes: AllowanceTarget, AnyInstanceAllowanceTarget, AnyInstanceExpectationTarget, ArgumentListMatcher, Configuration, Constant, ConstantMutator, Double, ExpectationTarget, MessageExpectation, Space, TargetBase, TestDoubleProxy

Constant Summary

KERNEL_METHOD_METHOD =

This constant is part of a private API. You should avoid using this constant if possible, as it may be removed or be changed in the future.

::Kernel.instance_method(:method)
DEPRECATED_CONSTANTS =
{
  :Mock            => Double,
  :ConstantStubber => ConstantMutator,
}
UnsupportedMatcherError =
Class.new(StandardError)
NegationUnsupportedError =
Class.new(StandardError)

Class Attribute Summary (collapse)

Class Method Summary (collapse)

Instance Method Summary (collapse)

Class Attribute Details

+ (Object) space

Returns the value of attribute space



7
8
9
# File 'lib/rspec/mocks.rb', line 7

def space
  @space
end

Class Method Details

+ (Object) allow_message(subject, message, opts = {})

Adds an allowance (stub) on subject

Examples:

Defines the implementation of foo on bar, using the passed block

x = 0
RSpec::Mocks.allow_message(bar, :foo) { x += 1 }

Parameters:

  • subject

    the subject to which the message will be added

  • message

    a symbol, representing the message that will be added.

  • opts (defaults to: {})

    a hash of options, :expected_from is used to set the original call site

  • block

    an optional implementation for the allowance



59
60
61
62
63
64
65
# File 'lib/rspec/mocks.rb', line 59

def allow_message(subject, message, opts={}, &block)
  orig_caller = opts.fetch(:expected_from) {
    CallerFilter.first_non_rspec_line
  }
  ::RSpec::Mocks.proxy_for(subject).
    add_stub(orig_caller, message.to_sym, opts, &block)
end

+ (Object) any_instance_recorder_for(klass)



43
44
45
# File 'lib/rspec/mocks.rb', line 43

def any_instance_recorder_for(klass)
  space.any_instance_recorder_for(klass)
end

+ (Object) configuration



76
77
78
# File 'lib/rspec/mocks/configuration.rb', line 76

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

+ (Object) const_missing(name)



117
118
119
120
121
122
123
124
# File 'lib/rspec/mocks.rb', line 117

def self.const_missing(name)
  if const = DEPRECATED_CONSTANTS[name]
    RSpec.deprecate("RSpec::Mocks::#{name}", :replacement => const.name)
    const
  else
    super
  end
end

+ (Object) expect_message(subject, message, opts = {})

Sets a message expectation on subject.

Examples:

Expect the message foo to receive bar, then call it

RSpec::Mocks.expect_message(bar, :foo)
bar.foo

Parameters:

  • subject

    the subject on which the message will be expected

  • message

    a symbol, representing the message that will be expected.

  • opts (defaults to: {})

    a hash of options, :expected_from is used to set the original call site

  • block

    an optional implementation for the expectation



78
79
80
81
82
83
84
# File 'lib/rspec/mocks.rb', line 78

def expect_message(subject, message, opts={}, &block)
  orig_caller = opts.fetch(:expected_from) {
    CallerFilter.first_non_rspec_line
  }
  ::RSpec::Mocks.proxy_for(subject).
    add_message_expectation(orig_caller, message.to_sym, opts, &block)
end

+ (Object) method_handle_for(object, method_name)

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.

Used internally to get a method handle for a particular object and method name.

Includes handling for a few special cases:

  • Objects that redefine #method (e.g. an HTTPRequest struct)
  • BasicObject subclasses that mixin a Kernel dup (e.g. SimpleDelegator)


97
98
99
100
101
102
103
# File 'lib/rspec/mocks.rb', line 97

def method_handle_for(object, method_name)
  if ::Kernel === object
    KERNEL_METHOD_METHOD.bind(object).call(method_name)
  else
    object.method(method_name)
  end
end

+ (Object) proxies_of(klass)



39
40
41
# File 'lib/rspec/mocks.rb', line 39

def proxies_of(klass)
  space.proxies_of(klass)
end

+ (Object) proxy_for(object)



35
36
37
# File 'lib/rspec/mocks.rb', line 35

def proxy_for(object)
  space.proxy_for(object)
end

+ (Object) setup(host = nil)



9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
# File 'lib/rspec/mocks.rb', line 9

def setup(host=nil)
  host_is_from_rspec_core = defined?(::RSpec::Core::ExampleGroup) && host.is_a?(::RSpec::Core::ExampleGroup)
  if host
    unless host_is_from_rspec_core
      RSpec.deprecate(
        "The host argument to `RSpec::Mocks.setup`",
        :replacement => "`include RSpec::Mocks::ExampleMethods` in #{host.inspect}"
      )
    end

    (class << host; self; end).class_eval do
      include RSpec::Mocks::ExampleMethods
    end
  end
  space.outside_example = false
end

+ (Object) teardown



30
31
32
33
# File 'lib/rspec/mocks.rb', line 30

def teardown
  space.reset_all
  space.outside_example = true
end

+ (Object) verify



26
27
28
# File 'lib/rspec/mocks.rb', line 26

def verify
  space.verify_all
end

Instance Method Details

- (Object) allow

Note:

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

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/syntax.rb', line 304

- (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/syntax.rb', line 324

- (Recorder) any_instance

Note:

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

Used to set stubs and message expectations on any instance of a given class. Returns a Recorder, which records messages like stub and should_receive for later playback on instances of the class.

Examples:

Car.any_instance.should_receive(:go)
race = Race.new
race.cars << Car.new
race.go # assuming this delegates to all of its cars
        # this example would pass

Account.any_instance.stub(:balance) { Money.new(:USD, 25) }
Account.new.balance # => Money.new(:USD, 25))

Returns:

  • (Recorder)


# File 'lib/rspec/mocks/syntax.rb', line 271

- (Object) as_null_object

Note:

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

Tells the object to respond to all messages. If specific stub values are declared, they'll work as expected. If not, the receiver is returned.



# File 'lib/rspec/mocks/syntax.rb', line 259

- (Object) expect

Note:

This method is usually provided by rspec-expectations, unless you are using rspec-mocks w/o rspec-expectations, in which case it is only made available if you enable the expect syntax.

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/syntax.rb', line 292

- (Object) expect_any_instance_of

Note:

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

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/syntax.rb', line 314

- (Object) null_object?

Note:

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

Returns true if this object has received as_null_object



# File 'lib/rspec/mocks/syntax.rb', line 266

- (Object) receive

Note:

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

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/syntax.rb', line 334

- (Object) should_not_receive

Sets and expectation that this object should not receive a message during this example.



# File 'lib/rspec/mocks/syntax.rb', line 202

- (Object) should_receive

Note:

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

Sets an expectation that this object should receive a message before the end of the example.

Examples:

logger = double('logger')
thing_that_logs = ThingThatLogs.new(logger)
logger.should_receive(:log)
thing_that_logs.do_something_that_logs_a_message


# File 'lib/rspec/mocks/syntax.rb', line 189

- (Object) stub

Note:

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

Tells the object to respond to the message with the specified value.

Examples:

counter.stub(:count).and_return(37)
counter.stub(:count => 37)
counter.stub(:count) { 37 }


# File 'lib/rspec/mocks/syntax.rb', line 206

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

Note:

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

Stubs a chain of methods.

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 stub_chain a code smell. Even though not all code smells indicate real problems (think fluent interfaces), stub_chain still results in brittle examples. For example, if you write foo.stub_chain(:bar, :baz => 37) in a spec and then the implementation calls foo.baz.bar, the stub will not work.

Examples:

double.stub_chain("foo.bar") { :baz }
double.stub_chain(:foo, :bar => :baz)
double.stub_chain(:foo, :bar) { :baz }

# Given any of ^^ these three forms ^^:
double.foo.bar # => :baz

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


# File 'lib/rspec/mocks/syntax.rb', line 228

- (Object) unstub

Note:

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

Removes a stub. On a double, the object will no longer respond to message. On a real object, the original method (if it exists) is restored.

This is rarely used, but can be useful when a stub is set up during a shared before hook for the common case, but you want to replace it for a special case.



# File 'lib/rspec/mocks/syntax.rb', line 217