Test Driven Development (and Why Your Tests Should Fail)
Most of us want to succeed on the first go round. When it comes to Test Driven Development, we want those happy little green dots to tell us that everything is perfect and we can take a nap.
Here’s the thing: If a test never fails, was it ever a test in the first place?
If you want to see if some of your code works, first make your test fail. In fact, write the test before you even write your code. This seems backwards, but it is SUPER beneficial for a few reasons:
- It will give you a target to aim for. Even for simple functions, having a target outcome gives you something to build at. This focuses your thinking, keeps your goals right in front of you, and makes you more efficient as a developer. Aim small, miss small.
- It will outline all of your goals. I commonly get so caught up in my projects that I end up leaving out bits of code that I should have included, mostly because I forgot I needed those outputs. These little red ‘F’s will make you build until its done.
- It will make you fail until you succeed. When you’re haphazardly coding based on the hope that something kind of works, you become horribly inefficient and you fall off the path, get frustrated, and then shut down. With TDD, your goals become a game, and you build until you reach 100% completion (and if you don’t, its your own fault).
In TDD this is called Red, Green, Refactor. Simply put:
- Red: Fail Everything. Blank code, full test suite. All of your tests should fail with big red ‘F’s. Once your test suite is complete, build your code, until you reach…
- Green: Build Until You Pass. Lots of little green dots should start popping up and you should start feeling little adrenaline shots of joy until you reach completion. When everything is green, you can improve your work with a thorough….
- Refactor: You did it, now do it better. Slim down and optimize your code.
With these methods, your builds should be faster, more efficient, and more effectively targeted.