Lee
Lee

Reputation: 9462

Should I mock my model in rails controller tests?

I am finding holes in my coverage because I have been mocking my models in controller examples. When I remove a model's method upon which a controller depends, I do not get a failure.

Coming from TDD in statically typed languages, I would always mock dependencies to the object under test that hit the database to increase speed. I would still get failures in the above example, since my mocks subclassed the original object. I am looking for best practices in a dynamic language.

Thanks.

UPDATE:

After getting a lot of conflicting opinions on this, it seems it boils down to which philosophy you buy into.

The Rspec community appears to embrace heavily stubbing dependencies to achieve isolation of the object under test. Acceptance tests (traditionally known as integration tests ;) are used to ensure your objects work with their runtime dependencies.

The shoulda / Test::Unit community appears to stay away from stubbing as much as possible. This allows your tests to confirm your object under test actually works with its dependencies.

This video summarizes this nicely: http://vimeo.com/3296561

Upvotes: 4

Views: 1403

Answers (3)

Sapna Jindal
Sapna Jindal

Reputation: 422

While writing unit tests, the whole aim should be test that unit only. Consider Model as one unit and cover it separately. Change in Model should not directly impact unit test coverage of controller.

Upvotes: 0

Mike
Mike

Reputation: 361

If you're using Mocha, the following should do it.

Mocha::Configuration.prevent(:stubbing_non_existent_method)

Upvotes: 2

Jonathan Julian
Jonathan Julian

Reputation: 12272

Yes, in your controller examples, mock your models. In your model examples, test your models.

Upvotes: 2

Related Questions