Course contentsShow
← Computer Science
Lesson 2256 of 2,87250. Software TestingFree lesson

The Red-Green-Refactor Cycle

Learn the core TDD workflow: write a failing test (red), make it pass (green), then refactor code while keeping tests green.

The Red-Green-Refactor Cycle

What you'll learn: You'll master the three-step rhythm that drives Test-Driven Development: writing a failing test first, making it pass quickly, then improving the code quality.

The Core Workflow

The Red-Green-Refactor cycle is the heartbeat of Test-Driven Development (TDD). It's a disciplined loop that ensures you write tests before code and continuously improve design without breaking functionality.

Think of it like sculpting: first you sketch what the sculpture should look like (red), then you carve out the basic shape (green), then you polish and refine the details (refactor).

Step 1: Red (Write a Failing Test)

Start by writing a test for functionality that doesn't exist yet. Run it—it must fail. This proves your test can actually catch problems and clarifies exactly what you're building.

def test_calculate_total():
    assert calculate_total([10, 20, 30]) == 60  # Function doesn't exist yet!

Step 2: Green (Make It Pass)

Write the simplest code possible to make the test pass. Don't worry about elegance—just get to green.

def calculate_total(items):
    return sum(items)  # Minimal implementation

Step 3: Refactor (Improve the Code)

Now that tests are passing (green), clean up the code. Rename variables, extract functions, eliminate duplication—all while keeping tests green. The tests are your safety net.

Why This Order Matters

Writing the test first forces you to think about requirements and design before implementation. The failing state (red) confirms your test works. Refactoring with green tests gives you confidence that improvements don't break behavior.

Key Takeaway: The Red-Green-Refactor cycle—fail, pass, improve—creates a tight feedback loop that produces well-tested, maintainable code through incremental development.