Ruby Testing – When Not to Use Test Doubles, Mocks, and Stubs in Ruby Rspec

mockingrubystubtesting

I've learned about mocking and stubbing and I've seen how they can help me create great test suites that run blindingly fast and thus speed up my development process hugely.

However I've also seen the downside when there is an issue that is database centred and wasn't tested for (test doubles or not).

So should I have a subset of tests that do test such connectivity at least and some simple operations, for example creating a record in the primary transaction detail table, even if most of the foreign keys are stubbed out?

What experience have people found with this issue and what balance has worked in various situations?

I normally post on Stack Overflow but this seemed much more conceptual. It might still be a bit subjective so maybe the question can be improved.

The closest similar question I could find was When should I use mock objects? but it didn't feel like it was really the same question and the answers felt further off. Perhaps my question is more about when NOT to mock. …yeah, so I've updated my title.

I also found this helpful: TDD: Mocking out tightly coupled objects

Best Answer

I see unit tests as routines that test pieces of code that are in a code base that you manage. Mocking and stubbing helps focus only on the flow and logic of your code, which is what you are testing in your unit tests.

Whether or not an outside service like a database (which is not inherently part of your code) actually works is not important for unit tests, but rather for integration tests.

So should I have a subset of tests that do test such connectivity at least and some simple operations, for example creating a record in the primary transaction detail table, even if most of the foreign keys are stubbed out?

Only if you have implemented routines to do simple database operations, should you tests whether those routines work like you expect them to, in unit tests. But then you would still stub out the database because you are not particularly interested in whether the database actually works, you are testing whether the logic in your code works.

Related Topic