The Red-Green-Refactor Loop
You'll learn: The three-phase TDD cycle that guides how to write tests first, make them pass, then improve your code.
The Core Rhythm of TDD
Test-Driven Development follows a simple, repeating cycle with three distinct phases:
Red: Write a test for functionality that doesn't exist yet. Run it and watch it fail (turn "red"). This confirms your test is actually testing something and isn't accidentally passing.
Green: Write the minimum code needed to make that test pass. Don't worry about elegance or perfection—just get to green as quickly as possible. This might mean writing naive or even "ugly" code, and that's okay.
Refactor: Now that you have a passing test as a safety net, improve the code's structure, readability, and design. Remove duplication, apply patterns you've learned, rename variables—whatever makes the code better. Run your tests frequently to ensure they still pass.
Then repeat: write another failing test, make it pass, refactor. Over and over.
Why This Rhythm Works
Think of it like sculpting: you first place a rough chunk of clay (Green), then shape and refine it (Refactor), but you need a guide to know what you're building (Red). The test is your guide.
This cycle keeps you focused. You're never writing untested code, never refactoring without a safety net, and never writing tests for code that already works (which would skip the valuable "Red" validation step).
The loop also creates natural checkpoints. Each green test is a small victory and a safe point to pause or change direction.
Key Takeaway: The Red-Green-Refactor loop—write a failing test, make it pass with minimal code, then refactor with confidence—is the fundamental rhythm that makes TDD both safe and effective.