class Mocha::Mock

Traditional mock object.

{expects} and {stubs} return an {Expectation} which can be further modified by methods on {Expectation}.

{responds_like} and {responds_like_instance_of} both return a {Mock}, and can therefore, be chained to the original creation methods in {API}. They force the mock to indicate what it is supposed to be mocking, thus making it a safer verifying mock. They check that the underlying responder will actually respond to the methods being stubbed, throwing a NoMethodError upon invocation otherwise.

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.

However, note that if the expectation that matches the invocation has a cardinality of “never”, then an unexpected invocation error is reported.

This scheme allows you to:

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

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.