Search⌘ K

Mock Tips

Explore techniques for using test doubles as mocks and stubs in Rails to isolate tests effectively. Understand best practices such as avoiding mocks of external frameworks, managing side effects, and minimizing false positives. Learn when to stub versus mock and how mocks can reveal code design quality.

Test doubles tips

Author’s note: My opinion about the best way to use mock objects changes every few months. I’ll try some mocks, see that they work well, so I start using more mocks, and they’ll start getting in the way, so I back off, and then I think, “Let’s try some mocks.” This cycle has been going for years, and I have no reason to think it’s going to change anytime soon.

However, some guidelines always hold. Let’s see what they are.

The ownership rule

We don’t mock what we don’t own. Instead, we use test doubles only to replace methods that are part of the application and not part of an external framework.

Note: We violated this rule in this chapter when we stubbed ActiveRecord methods like update_attributes. Again, Don’t mock what we don’t own.

Frameworks and mocks

One reason to mock only methods we control is, well, that we control them. One danger in mocking methods is that the mock either doesn’t receive or doesn’t return a reasonable ...