ruby-on-railsrspec

Using rspec, confused as to difference between a mock and a stub object?


What is the difference between a mock and a stub, they both seem very similar to me?

It would be nice if someone could give a real world example of when to use which, or are they interchangeable but there is a best-practise like when to use a mock or a stub?


Solution

  • This is the reference in most articles, pretty generic and clear explanation:

    http://martinfowler.com/articles/mocksArentStubs.html

    In a nutshell:

    Stubs provide canned answers to calls made during the test, usually not responding at all to anything outside what's programmed in for the test. Stubs may also record information about calls, such as an email gateway stub that remembers the messages it 'sent', or maybe only how many messages it 'sent'.

    And

    Mocks are objects pre-programmed with expectations which form a specification of the calls they are expected to receive.