The Loop

Three steps, in order, repeated.

Red. Write a test for behavior that does not exist yet. Run it. Watch it fail, and check it fails for the reason you expected.

Green. Write the simplest code that makes it pass. Not the good code. The simplest.

Refactor. Now make it good, with the test holding you to the behavior.

The order is the whole technique. Doing the same three things in a different order is not TDD, it is writing tests.

Why watch it fail? Because a test you have never seen fail is a test you have no reason to trust.

A test with a typo in the name of the thing it imports passes vacuously. A test asserting nothing passes. A test in a file the runner never picks up passes by not existing. All three look identical to a passing suite, and all three are common. Watching red is how you find out the test is wired up.

✦ The real benefit is design pressure

Writing the test first forces you to use the thing before it exists, which means deciding its interface from the outside. Code that is awkward to test is usually code that is awkward to use, and TDD makes you feel that at the point where changing it is free. That is a larger benefit than the tests themselves.

Mark this lesson complete

Signed in, your progress follows you to every device.

Next: Doing It →
← Back