Master TDD by predicting the future
You’ve got a pretty good idea of how to do TDD – red-green-refactor – but still have trouble implementing it in practice. Your tests fail, and you don’t know why. When you try to make them pass, they don’t. No matter how hard you try, TDD still seems out of reach.
Don’t worry – TDD can take a little while to get the hang of. But I’ve got something to share with you that will help you out big time. It’s a simple process that I follow every single time I do TDD. And if you follow it, you’ll understand TDD better than ever.
I call it…
Predicting the future
Unlike fortune telling, this is a kind of predicting the future that you can actually do. Here’s how it works:
- Before you run the test, state out loud whether it will pass or fail.
- If you think it will fail, state out loud the failure message, and…
- State out loud the reason why the failure message will occur.
I do this every single time I make a change. Here’s an example:
Before running the test, I will say (out loud), this test will fail, with an undefined method error, because the
#meaning_of_life method doesn’t exist in
MyClass. Then I’ll make a tiny change to the code, which will change the message:
Now I’ll say (out loud, before running the test), the test will fail with the message,
Expected 42, got nil, because the
#meaning_of_life method doesn’t return anything. Finally, after making the change that will pass the test, I’ll say out loud, “The test will pass.” Here’s the test:
It take two seconds, and helps you clarify your thinking big time.
You’re building a mental model of how the software works
Predicting the future helps you determine how accurate your mental model is, compared to the code.
If you predict incorrectly, don’t worry. It’s an opportunity to improve your mental model. Just take a moment to understand the difference between what you expected to happen, and what actually happened. It’s usually pretty simple. And then you try again.
I can’t stress enough how valuable this process is to me. I predict the outcome of every single test I write. If you practice this consistently, you’ll find your understanding of TDD deepens every time you run a test.