Learn / macOS

Learn the red–green–refactor cycle

Connect a behavioral requirement to a test and carry that habit into TDD Practice.

TDD learning with the lesson catalog and worked red–green–refactor example.
TDD learning with the lesson catalog and worked red–green–refactor example. Select the image to enlarge.
  1. Name one behavior

    Read the worked example and state what the caller should observe. Avoid depending on implementation details in the expectation.

    Example

    A count function returns zero when given an empty array. The test describes the result regardless of whether the implementation uses a loop.

  2. Explain each phase

    Complete the drill by identifying what Red, Green, and Refactor prove. Predict which change should make the failing test pass.

    Example

    Red proves that the missing behavior is detected. Green introduces the behavior. Refactor changes structure while preserving the checks.

  3. Practice with a small contract

    Open TDD Practice and choose an exercise. Write one failing test before editing the implementation.

    Example

    For a duplicate-counting task, add a repeated-value case, make it pass, then simplify the accumulator without changing the output.

Check your work

You can explain why your first failing test was useful and show the result after refactoring.

Try it yourself

Before implementing a validator for a text field, write a boundary test for the longest accepted input and a separate test for one character beyond it. Use the lesson to predict what each test establishes.

What to look for
Each test should identify the behavior at a different boundary. When the implementation changes, both tests should still express the same contract.