Topic: mock, stub etc...


I have read the rspec book, and despite there being a chapter devoted to mocks, I still am a bit confused on how they work exactly.  I am hoping someone here can break it down for me with some examples of how they use mocks and stubs-- when to use one over the other.

I am also a subscriber of peepcode, and have watched the rspec screencast--  In that, it was explained that stubs are identical to mocks except there is no expectation of a returned result... ?  Is this correct?

I thought that made sense until I was watching a railsconf screencast on bdd and I saw:

user = mock_model(User, :wishes => mock("wishes association"))

Which totally confused me because the stub is returning user-- which is an expectation, is it not?

I am also quite confused on what the difference is between mock_model() and mock()...

From the looks of that code, it looks like user = mock_model is creating an object that acts just like the User model-- and as far as the :wishes => mock("wishes association") ..  I have no idea what that means.  I would think mock by itself would mean that it's mocking a method, but-- what would be the point of that?  If you have a fake object that acts just like the real thing, why not just use the actual methods of the real thing?

My final question regarding this stuff would be, if mock_model is done to create an object that behaves just like the real thing, then why does there need to be a test database?  I though a test database was so that your actual models can write test data to a test specific environment and not interfere with your real data..  So if that's true, why are mocks helpful?  Why not just use the real object and write to the test database?

Sooo confused!


Re: mock, stub etc...

I can't say it better than this: … ksAndStubs

Re: mock, stub etc...

I found this presentation helpful. Near the end mocks and stubs are compared.

Stubs - A function with a canned response
Mocks - An object with canned responses (can have many stubs)

My limited understanding (as I'm just learning too) is that you can use stubs to represent a simple object but if you want to do anything interesting with it you'll want to use a mock. Does that sound right to all the silent experts out there?

As for mock vs. mock_model; mock_model creates a mock of an active record model object while mock returns a plain old ruby object.

As for :wishes => mock("wishes association"), I dont have a clue. It looks like wishes should return an object representing the string "wishes association"... ?

Anyway, your not alone... I'm trying to figure this out too!