Class: Mocha::Mock

### Home Classes Methods

### In Files

- lib/mocha/mock.rb

### Parent

Object

### Methods

- ::new
- #__expectations__
- #__expects__
- #__stubs__
- #__verified__?
- #all_expectations
- #any_expectations?
- #ensure_method_not_already_defined
- #expects
- #inspect
- #method_missing
- #mocha_inspect
- #quacks_like
- #quacks_like_instance_of
- #respond_to?
- #responds_like
- #responds_like_instance_of
- #stub_everything
- #stubs
- #unstub

### Class/Module Index

Quicksearch

- Mocha
- Mocha::API
- Mocha::AnyInstanceMethod
- Mocha::AnyInstanceReceiver
- Mocha::ArgumentIterator
- Mocha::ArrayMethods
- Mocha::BacktraceFilter
- Mocha::Cardinality
- Mocha::Central
- Mocha::ChangeStateSideEffect
- Mocha::ClassMethod
- Mocha::ClassMethods
- Mocha::ClassMethods::AnyInstance
- Mocha::Configuration
- Mocha::DateMethods
- Mocha::Debug
- Mocha::DefaultName
- Mocha::DefaultReceiver
- Mocha::Deprecation
- Mocha::Detection
- Mocha::Detection::MiniTest
- Mocha::Detection::TestUnit
- Mocha::ExceptionRaiser
- Mocha::Expectation
- Mocha::ExpectationError
- Mocha::ExpectationErrorFactory
- Mocha::ExpectationList
- Mocha::HashMethods
- Mocha::Hooks
- Mocha::ImpersonatingAnyInstanceName
- Mocha::ImpersonatingName
- Mocha::InStateOrderingConstraint
- Mocha::InstanceMethod
- Mocha::Integration
- Mocha::Integration::AssertionCounter
- Mocha::Integration::MiniTest
- Mocha::Integration::MiniTest::Adapter
- Mocha::Integration::MiniTest::Nothing
- Mocha::Integration::MiniTest::Version13
- Mocha::Integration::MiniTest::Version13::RunMethodPatch
- Mocha::Integration::MiniTest::Version140
- Mocha::Integration::MiniTest::Version140::RunMethodPatch
- Mocha::Integration::MiniTest::Version141
- Mocha::Integration::MiniTest::Version141::RunMethodPatch
- Mocha::Integration::MiniTest::Version142To172
- Mocha::Integration::MiniTest::Version142To172::RunMethodPatch
- Mocha::Integration::MiniTest::Version200
- Mocha::Integration::MiniTest::Version200::RunMethodPatch
- Mocha::Integration::MiniTest::Version201To222
- Mocha::Integration::MiniTest::Version201To222::RunMethodPatch
- Mocha::Integration::MiniTest::Version2110To2111
- Mocha::Integration::MiniTest::Version2110To2111::RunMethodPatch
- Mocha::Integration::MiniTest::Version2112To320
- Mocha::Integration::MiniTest::Version2112To320::RunMethodPatch
- Mocha::Integration::MiniTest::Version230To2101
- Mocha::Integration::MiniTest::Version230To2101::RunMethodPatch
- Mocha::Integration::MonkeyPatcher
- Mocha::Integration::TestUnit
- Mocha::Integration::TestUnit::Adapter
- Mocha::Integration::TestUnit::GemVersion200
- Mocha::Integration::TestUnit::GemVersion200::RunMethodPatch
- Mocha::Integration::TestUnit::GemVersion201To202
- Mocha::Integration::TestUnit::GemVersion201To202::RunMethodPatch
- Mocha::Integration::TestUnit::GemVersion203To220
- Mocha::Integration::TestUnit::GemVersion203To220::RunMethodPatch
- Mocha::Integration::TestUnit::GemVersion230To250
- Mocha::Integration::TestUnit::GemVersion230To250::RunMethodPatch
- Mocha::Integration::TestUnit::Nothing
- Mocha::Integration::TestUnit::RubyVersion185AndBelow
- Mocha::Integration::TestUnit::RubyVersion185AndBelow::RunMethodPatch
- Mocha::Integration::TestUnit::RubyVersion186AndAbove
- Mocha::Integration::TestUnit::RubyVersion186AndAbove::RunMethodPatch
- Mocha::Logger
- Mocha::MethodMatcher
- Mocha::Mock
- Mocha::Mockery
- Mocha::ModuleMethod
- Mocha::ModuleMethods
- Mocha::MultipleYields
- Mocha::Name
- Mocha::NoYields
- Mocha::ObjectMethods
- Mocha::ObjectReceiver
- Mocha::ParameterMatchers
- Mocha::ParameterMatchers::AllOf
- Mocha::ParameterMatchers::AnyOf
- Mocha::ParameterMatchers::AnyParameters
- Mocha::ParameterMatchers::Anything
- Mocha::ParameterMatchers::Base
- Mocha::ParameterMatchers::Equals
- Mocha::ParameterMatchers::HasEntries
- Mocha::ParameterMatchers::HasEntry
- Mocha::ParameterMatchers::HasKey
- Mocha::ParameterMatchers::HasValue
- Mocha::ParameterMatchers::Includes
- Mocha::ParameterMatchers::InstanceOf
- Mocha::ParameterMatchers::IsA
- Mocha::ParameterMatchers::KindOf
- Mocha::ParameterMatchers::Not
- Mocha::ParameterMatchers::Optionally
- Mocha::ParameterMatchers::QueryStringMatches
- Mocha::ParameterMatchers::RegexpMatches
- Mocha::ParameterMatchers::RespondsWith
- Mocha::ParameterMatchers::YamlEquivalent
- Mocha::ParametersMatcher
- Mocha::PrettyParameters
- Mocha::ReturnValues
- Mocha::Sequence
- Mocha::Sequence::InSequenceOrderingConstraint
- Mocha::SingleReturnValue
- Mocha::SingleYield
- Mocha::StateMachine
- Mocha::StateMachine::State
- Mocha::StateMachine::StatePredicate
- Mocha::StringMethods
- Mocha::StubbingError
- Mocha::Thrower
- Mocha::TimeMethods
- Mocha::UnexpectedInvocation
- Mocha::YieldParameters
- Array
- Date
- Hash
- Object
- String
- Time

No matching classes.

# Mocha::Mock

Traditional mock object.

All methods return an {Expectation} which can be further modified by methods on {Expectation}.

Stubs and expectations are basically the same thing. A stub is just an expectation of zero or more invocations. The {stubs} method is syntactic sugar to make the intent of the test more explicit.

When a method is invoked on a mock object, the mock object searches through its expectations from newest to oldest to find one that matches the invocation. After the invocation, the matching expectation might stop matching further invocations. For example, an +expects(:foo).once+ expectation only matches once and will be ignored on future invocations while an +expects(:foo).at_least_once+ expectation will always be matched against invocations.

This scheme allows you to:

- Set up default stubs in your the `setup` method of your test class and override some of those stubs in individual tests.

- Set up different `once` expectations for the same method with different action per invocation. However, it's better to use the {Expectation#returns} method with multiple arguments to do this, as described below.

However, there are some possible "gotchas" caused by this scheme:

- if you create an expectation and then a stub for the same method, the stub will always override the expectation and the expectation will never be met.

- if you create a stub and then an expectation for the same method, the expectation will match, and when it stops matching the stub will be used instead, possibly masking test failures.

- if you create different expectations for the same method, they will be invoked in the opposite order than that in which they were specified, rather than the same order.

The best thing to do is not set up multiple expectations and stubs for the same method with exactly the same matchers. Instead, use the {Expectation#returns} method with multiple arguments to create multiple actions for a method. You can also chain multiple calls to {Expectation#returns} and {Expectation#raises} (along with syntactic sugar {Expectation#then} if desired).

@example

    object = mock()
    object.stubs(:expected_method).returns(1, 2).then.raises(Exception)
    object.expected_method # => 1
    object.expected_method # => 2
    object.expected_method # => raises exception of class Exception1

If you want to specify more complex ordering or order invocations across different mock objects, use the {Expectation#in_sequence} method to explicitly define a total or partial ordering of invocations.

### Attributes

everything_stubbed[R]

@private

### Public Class Methods

new(mockery, name = nil, receiver = nil, &block) click to toggle source

@private

    # File lib/mocha/mock.rb, line 254
    def initialize(mockery, name = nil, receiver = nil, &block)
      @mockery = mockery
      @name = name || DefaultName.new(self)
      @receiver = receiver || DefaultReceiver.new(self)
      @expectations = ExpectationList.new
      @everything_stubbed = false
      @responder = nil
      @unexpected_invocation = nil
      instance_eval(&block) if block
    end

### Public Instance Methods

__expectations__() click to toggle source

@private

    # File lib/mocha/mock.rb, line 276
    def __expectations__
      @expectations
    end

__expects__(method_name_or_hash, backtrace = nil) click to toggle source
Alias for: expects
__stubs__(method_name_or_hash, backtrace = nil) click to toggle source
Alias for: stubs
__verified__?(assertion_counter = nil) click to toggle source

@private

    # File lib/mocha/mock.rb, line 326
    def __verified__?(assertion_counter = nil)
      @expectations.verified?(assertion_counter)
    end

all_expectations() click to toggle source

@private

    # File lib/mocha/mock.rb, line 286
    def all_expectations
      @receiver.mocks.inject(ExpectationList.new) { |e, m| e + m.__expectations__ }
    end

any_expectations?() click to toggle source

@private

    # File lib/mocha/mock.rb, line 346
    def any_expectations?
      @expectations.any?
    end

ensure_method_not_already_defined(method_name) click to toggle source

@private

    # File lib/mocha/mock.rb, line 341
    def ensure_method_not_already_defined(method_name)
      self.__metaclass__.send(:undef_method, method_name) if self.__metaclass__.method_defined?(method_name) || self.__metaclass__.private_method_defined?(method_name)
    end

expects(method_name_or_hash, backtrace = nil) click to toggle source

Adds an expectation that the specified method must be called exactly once with any parameters.

@param [Symbol,String] method_name name of expected method @param [Hash] expected_methods_vs_return_values expected method name symbols as keys and corresponding return values as values - these expectations are setup as if {expects} were called multiple times.

@overload def expects(method_name) @overload def expects(expected_methods_vs_return_values) @return [Expectation] last-built expectation which can be further modified by methods on {Expectation}.

@example Expected method invoked once so no error raised

    object = mock()
    object.expects(:expected_method)
    object.expected_method

@example Expected method not invoked so error raised

    object = mock()
    object.expects(:expected_method)
    # error raised when test completes, because expected_method not called exactly once

@example Expected method invoked twice so error raised

    object = mock()
    object.expects(:expected_method)
    object.expected_method
    object.expected_method # => error raised when expected method invoked second time

@example Setup multiple expectations using `expected_methods_vs_return_values`.

    object = mock()
    object.expects(:expected_method_one => :result_one, :expected_method_two => :result_two)

    # is exactly equivalent to

    object = mock()
    object.expects(:expected_method_one).returns(:result_one)
    object.expects(:expected_method_two).returns(:result_two)

    # File lib/mocha/mock.rb, line 105
    def expects(method_name_or_hash, backtrace = nil)
      iterator = ArgumentIterator.new(method_name_or_hash)
      iterator.each { |*args|
        method_name = args.shift
        ensure_method_not_already_defined(method_name)
        expectation = Expectation.new(self, method_name, backtrace)
        expectation.returns(args.shift) if args.length > 0
        @expectations.add(expectation)
      }
    end

Also aliased as: __expects__
inspect() click to toggle source

@private

    # File lib/mocha/mock.rb, line 336
    def inspect
      mocha_inspect
    end

method_missing(symbol, *arguments, &block) click to toggle source

@private

    # File lib/mocha/mock.rb, line 291
    def method_missing(symbol, *arguments, &block)
      if @responder and not @responder.respond_to?(symbol)
        raise NoMethodError, "undefined method `#{symbol}' for #{self.mocha_inspect} which responds like #{@responder.mocha_inspect}"
      end
      if matching_expectation_allowing_invocation = all_expectations.match_allowing_invocation(symbol, *arguments)
        matching_expectation_allowing_invocation.invoke(&block)
      else
        if (matching_expectation = all_expectations.match(symbol, *arguments)) || (!matching_expectation && !@everything_stubbed)
          if @unexpected_invocation.nil?
            @unexpected_invocation = UnexpectedInvocation.new(self, symbol, *arguments)
            matching_expectation.invoke(&block) if matching_expectation
            message = @unexpected_invocation.full_description
            message << @mockery.mocha_inspect
          else
            message = @unexpected_invocation.short_description
          end
          raise ExpectationErrorFactory.build(message, caller)
        end
      end
    end

mocha_inspect() click to toggle source

@private

    # File lib/mocha/mock.rb, line 331
    def mocha_inspect
      @name.mocha_inspect
    end

quacks_like(responder) click to toggle source
Alias for: responds_like
quacks_like_instance_of(responder_class) click to toggle source
Alias for: responds_like_instance_of
respond_to?(symbol, include_private = false) click to toggle source

@private

    # File lib/mocha/mock.rb, line 313
    def respond_to?(symbol, include_private = false)
      if @responder then
        if @responder.method(:respond_to?).arity > 1
          @responder.respond_to?(symbol, include_private)
        else
          @responder.respond_to?(symbol)
        end
      else
        @everything_stubbed || all_expectations.matches_method?(symbol)
      end
    end

responds_like(responder) click to toggle source

Constrains the {Mock} instance so that it can only expect or stub methods to which `responder` responds. The constraint is only applied at method invocation time.

A `NoMethodError` will be raised if the `responder` does not `#respond_to?` a method invocation (even if the method has been expected or stubbed).

The {Mock} instance will delegate its `#respond_to?` method to the `responder`.

Note that the methods on `responder` are never actually invoked.

@param [Object, respond_to?] responder an object used to determine whether {Mock} instance should `#respond_to?` to an invocation. @return [Mock] the same {Mock} instance, thereby allowing invocations of other {Mock} methods to be chained. @see responds_like_instance_of

@example Normal mocking

    sheep = mock('sheep')
    sheep.expects(:chew)
    sheep.expects(:foo)
    sheep.respond_to?(:chew) # => true
    sheep.respond_to?(:foo) # => true
    sheep.chew
    sheep.foo
    # no error raised

@example Using {responds_like} with an instance method

    class Sheep
      def chew(grass); end
    end

    sheep = mock('sheep')
    sheep.responds_like(Sheep.new)
    sheep.expects(:chew)
    sheep.expects(:foo)
    sheep.respond_to?(:chew) # => true
    sheep.respond_to?(:foo) # => false
    sheep.chew
    sheep.foo # => raises NoMethodError exception

@example Using {responds_like} with a class method

    class Sheep
      def self.number_of_legs; end
    end

    sheep_class = mock('sheep_class')
    sheep_class.responds_like(Sheep)
    sheep_class.stubs(:number_of_legs).returns(4)
    sheep_class.expects(:foo)
    sheep_class.respond_to?(:number_of_legs) # => true
    sheep_class.respond_to?(:foo) # => false
    sheep_class.number_of_legs # => 4
    sheep_class.foo # => raises NoMethodError exception

    # File lib/mocha/mock.rb, line 216
    def responds_like(responder)
      @responder = responder
      self
    end

Also aliased as: quacks_like
responds_like_instance_of(responder_class) click to toggle source

Constrains the {Mock} instance so that it can only expect or stub methods to which an instance of the `responder_class` responds. The constraint is only applied at method invocation time. Note that the responder instance is instantiated using +Class#allocate+.

A `NoMethodError` will be raised if the responder instance does not `#respond_to?` a method invocation (even if the method has been expected or stubbed).

The {Mock} instance will delegate its `#respond_to?` method to the responder instance.

Note that the methods on the responder instance are never actually invoked.

@param [Class] responder_class a class used to determine whether {Mock} instance should `#respond_to?` to an invocation. @return [Mock] the same {Mock} instance, thereby allowing invocations of other {Mock} methods to be chained. @see responds_like

@example Using {responds_like_instance_of}

    class Sheep
      def initialize
        raise "some awkward code we don't want to call"
      end
      def chew(grass); end
    end

    sheep = mock('sheep')
    sheep.responds_like_instance_of(Sheep)
    sheep.expects(:chew)
    sheep.expects(:foo)
    sheep.respond_to?(:chew) # => true
    sheep.respond_to?(:foo) # => false
    sheep.chew
    sheep.foo # => raises NoMethodError exception

    # File lib/mocha/mock.rb, line 249
    def responds_like_instance_of(responder_class)
      responds_like(responder_class.allocate)
    end

Also aliased as: quacks_like_instance_of
stub_everything() click to toggle source

@private

    # File lib/mocha/mock.rb, line 281
    def stub_everything
      @everything_stubbed = true
    end

stubs(method_name_or_hash, backtrace = nil) click to toggle source

Adds an expectation that the specified method may be called any number of times with any parameters.

@param [Symbol,String] method_name name of stubbed method @param [Hash] stubbed_methods_vs_return_values stubbed method name symbols as keys and corresponding return values as values - these stubbed methods are setup as if {stubs} were called multiple times.

@overload def stubs(method_name) @overload def stubs(stubbed_methods_vs_return_values) @return [Expectation] last-built expectation which can be further modified by methods on {Expectation}.

@example No error raised however many times stubbed method is invoked

    object = mock()
    object.stubs(:stubbed_method)
    object.stubbed_method
    object.stubbed_method
    # no error raised

@example Setup multiple expectations using `stubbed_methods_vs_return_values`.

    object = mock()
    object.stubs(:stubbed_method_one => :result_one, :stubbed_method_two => :result_two)

    # is exactly equivalent to

    object = mock()
    object.stubs(:stubbed_method_one).returns(:result_one)
    object.stubs(:stubbed_method_two).returns(:result_two)

    # File lib/mocha/mock.rb, line 141
    def stubs(method_name_or_hash, backtrace = nil)
      iterator = ArgumentIterator.new(method_name_or_hash)
      iterator.each { |*args|
        method_name = args.shift
        ensure_method_not_already_defined(method_name)
        expectation = Expectation.new(self, method_name, backtrace)
        expectation.at_least(0)
        expectation.returns(args.shift) if args.length > 0
        @expectations.add(expectation)
      }
    end

Also aliased as: __stubs__
unstub(method_name) click to toggle source

Removes the specified stubbed method (added by calls to {expects} or {stubs}) and all expectations associated with it.

@param [Symbol] method_name name of method to unstub.

@example Invoking an unstubbed method causes error to be raised

    object = mock('mock') do
    object.stubs(:stubbed_method).returns(:result_one)
    object.stubbed_method # => :result_one
    object.unstub(:stubbed_method)
    object.stubbed_method # => unexpected invocation: #<Mock:mock>.stubbed_method()

    # File lib/mocha/mock.rb, line 163
    def unstub(method_name)
      @expectations.remove_all_matching_method(method_name)
    end

[Validate]

Generated with the Darkfish Rdoc Generator 2.