Test-Driven Development
The Red-Green-Refactor Cycle
Master the fundamental rhythm of TDD — Red (failing test), Green (make it pass), Refactor (improve the design).
The Three Colors
The Red-Green-Refactor cycle is the heartbeat of TDD:
Red — Write a failing test. The test describes a new requirement. It fails because the code doesn't implement it yet. A failing test is good — it proves the test is actually testing something.
Green — Write the minimum code to pass the test. The simplest, dumbest code that makes the test pass. Resist the urge to build the "real" solution.
Refactor — Improve the code without changing behavior. Extract duplication, improve naming, simplify structure. Tests verify you didn't break anything.
Why "Minimum Code"?
If you solve everything at once, you cannot tell which part of your solution is actually needed. Baby steps guarantee each test drives a real requirement.
Triangulation
Sometimes a single test case can be satisfied by trivial code that doesn't generalize. Add a second test case that forces the real implementation.
Keeping the Rhythm
Each Red-Green-Refactor cycle should take 1-5 minutes. If a cycle is taking longer:
- The step is too large — break it into smaller steps
- The code is too complex — simplify the design
- The test is testing too much — test one thing at a time
Key Takeaways
- Red = failing test, Green = minimum code to pass, Refactor = improve without changing behavior
- "Minimum code" means the simplest code that passes — this reveals what is actually needed
- Triangulation: add a second test case to force generalization
- Each cycle should take 1-5 minutes — longer means the step is too big
Example
// Complete Red-Green-Refactor example