Last Updated: September 09, 2019
·
1.161K
· brianriley

Don't write more test code than you need

If there's one thing everyone knows about TDD, it's that you don't write any production code until you have a failing test. But that's only one third of TDD. There are actually two other rules of TDD:

You are not allowed to write any more of a unit test than is sufficient to fail; and compilation failures are failures.

and

You are not allowed to write any more production code than is sufficient to pass the one failing unit test.

These two rules require a particularly uncomfortable mental shift that it's rare to meet a programmer who follows them. Programmers hate seeing duplication, and we know we're going to need certain things in the future. But TDD is about a very tight feedback loop, which we delay by spending time writing code that we don't need right now to get that feedback.

So let's look a little at that second rule. Learn to follow the second rule, and the third rule will come naturally.

If you're writing specs, this means no lets, no befores, no subjects. It means no including of shared contexts, no setting up of records in your database. As much as it will offend our senses, it means letting duplication pile up (a little) and writing plain old Ruby in our it blocks. Save all of these rspec details for the refactoring step when your tests are green.

Right now you need a failing test. Right now, you need no more than a describe (for a new spec), an it, and an expectation. Run the test and watch it fail. Fix only that failure and run the test again; fix only that failure and run the test again; repeat until you're green.

Do this over and over, and you'll find yourself in the rhythm of TDD, where it will suddenly feel uncomfortable to write any more code than is needed to get more feedback from your tests.

1 Response
Add your response

do we really need TDD ? I still can't understand. is there a connection with the continues integration?

over 1 year ago ·