Sub topic 2
The red-green-refactor cycle
This chapter covers the working model of test-driven development (TDD) and how it changes when a coding agent writes much of the code. It assumes you can write basic Python, have run unit tests with a framework such as pytest, and know Git commits and diffs. You should also have used a coding agent at least once.
What the cycle is
TDD is a way of building software in short loops. Each loop has three phases, and the order never changes.
- Red. Write one test for a behavior that does not exist yet. Run it and watch it fail.
- Green. Write the smallest change that makes that test pass. Run the whole suite.
- Refactor. Clean up the code and the tests while every test stays green. Run the suite again.
Then you start the next loop with a new test. The names come from the color a test runner shows: red for failing, green for passing.
The cycle is useful because each phase has one job and one check. In red, the check is that the test fails. In green, the check is that everything passes. In refactor, the check is that nothing changed in behavior. You never need to hold more than one question in your head.
Why this suits a coding agent
An agent works by reading code, editing it, running commands, and reading the output. A test suite gives it two things it otherwise lacks.
- A specification it can execute. A prose request like "make slugify handle punctuation" can be read many ways. A test with a concrete input and expected output has one reading.
- A feedback signal it can read. The runner output tells the agent whether the last edit worked. Without it, the agent has to guess, and a guess that looks plausible is the main source of agent bugs.
The cycle also limits the size of each edit. A small, specific failing test pushes the agent toward a small, specific change that you can review in a minute.
A worked example: slugify
A slug is the URL-safe form of a title, such as hello-world. We will build a slugify function one behavior at a time.
Red: the first test
Write the test before any implementation exists.
# test_slugify.py
from slugify_util import slugify
def test_lowercases_and_joins_words_with_hyphens():
assert slugify("Hello World") == "hello-world"Run it with the command the agent will use after every change.
python -m pytest -qAt this point slugify_util.py does not exist, so the failure is an ImportError or ModuleNotFoundError. That is red, but it is red for the wrong reason. The test has not yet shown that it can detect a missing behavior. Create the module with a stub that does nothing useful.
# slugify_util.py
def slugify(text):
return NoneNow the output shows an AssertionError such as assert None == 'hello-world'. This is the failure you want, because it says the behavior is missing and the test is wired correctly. Section "Check why it fails" below covers this in more detail.
Green: the smallest change
Write the least code that passes.
# slugify_util.py
def slugify(text):
return text.lower().replace(" ", "-")Run the suite. One test passes. The implementation is deliberately naive. It ignores punctuation and repeated separators, because no test requires that yet. Handling those cases now would be writing behavior with no test behind it.
The next cycles
Each new behavior gets its own red-green loop. Add one test, watch it fail, then change the code.
# test_slugify.py (added in the next cycles)
def test_strips_punctuation():
assert slugify("Hello, World!") == "hello-world"
def test_collapses_repeated_separators():
assert slugify("a -- b") == "a-b"With the naive implementation, the first of these returns "hello,-world!" and the second returns "a-----b". Both fail with a clear difference between actual and expected values, which is what you want to see.
Refactor: clean up with a safety net
After both tests pass, you may find that patching the naive version would produce a pile of special cases. With three green tests in place, you can replace the approach safely.
# slugify_util.py after the later cycles and a refactor
import re
def slugify(text):
words = re.findall(r"[a-z0-9]+", text.lower())
return "-".join(words)This version extracts runs of letters and digits and joins them with hyphens. Punctuation and repeated separators disappear as a side effect of the approach, with no special handling. Run the suite again. If any test fails, the refactor changed behavior, and you undo it.
Check why it fails
The most skipped step in red is confirming the reason for the failure. A red test can fail for three kinds of reason.
| Failure | Typical output | What it means |
|---|---|---|
| Import or syntax error | `ModuleNotFoundError`, `SyntaxError` | The test never ran. It proves nothing about behavior. |
| Wrong setup or typo | `NameError`, `TypeError` from a bad call | The test is broken, not the code. |
| Assertion failure | `AssertionError` with actual and expected values | The behavior is missing. This is the intended red. |
Only the last row counts. A test that fails with an import error will also "pass" later for reasons unrelated to your intent, if you fix the import and the code happens to return the right value. Ask yourself whether the failure message describes the missing behavior in the words of your requirement.
A related risk is a test that passes immediately. If a new test is green before you write any code, either the behavior already exists or the test asserts nothing useful. Investigate before moving on.
Green means minimal, not clever
The green phase asks for the smallest change that passes. This is a discipline, not a style preference. It keeps the code driven by tests, so every line exists because some test needed it.
Agents tend to over-deliver here. Asked to make one test pass, an agent may add input validation, extra options, or handling for cases you did not ask about. That code is untested, and you now own it. You prevent this by telling the agent explicitly to write the smallest change.
The opposite problem: gaming the test
Minimal does not mean passing by any means. Consider this implementation.
# A degenerate 'green' an agent might produce
def slugify(text):
return "hello-world"It passes the first test. It also contains no logic. It fails the other two tests, which is why a suite needs several varied examples for the same function. When you see an implementation that mirrors test values, the fix is another test with different inputs, not a longer conversation. Later chapters cover this failure mode and how to prevent it in detail.
Refactoring rules
Refactoring means changing structure without changing behavior. The tests define what behavior means, so the rules are short.
- Refactor only when the suite is green. If a test is red, you are fixing, not refactoring.
- Run the suite after each refactoring step, not once at the end.
- Do not add new behavior during a refactor. New behavior needs a new red test first.
- Do not change tests and production code in the same step. If both change, a pass tells you nothing.
With an agent, the last rule matters most. If the agent edits a test during a refactor, the safety net has moved.
Telling the agent to follow the cycle
An agent will not follow TDD by default. It will usually write the implementation first and add tests afterward, if at all. You need to state the workflow. A short instruction file in your repository does this well.
## Working agreement for this repository
1. Work test-first. Write one failing test for the requested behavior and run it.
2. Show the failure output and confirm it fails because the behavior is missing, not because of a typo or import error.
3. Write the smallest change that makes that test pass, then run the full test suite.
4. Refactor only while all tests are green, and run the suite again afterwards.
5. Do not edit, skip, or delete existing tests to make them pass. If a test seems wrong, stop and explain why.
6. Do not hardcode expected values from tests into the implementation.Each rule maps to a check from this chapter. Rules 1 and 2 define red. Rule 3 defines green. Rule 4 defines refactor. Rules 5 and 6 guard against the agent gaming the loop.
Who does what
You can split the work in different ways. Two common patterns:
- You write the test, the agent implements. You control the specification. The agent handles green and, with supervision, refactor. This is the safest pattern when the requirement is subtle.
- The agent proposes the test, you approve it. The agent drafts the failing test and shows the red output. You read the test before it writes any implementation. This is faster and still keeps you in charge of what the test claims.
In both patterns, a human reads the test before green begins. The test is the part of the work that encodes intent, and an agent that writes both test and code from one misunderstanding will produce a green suite that is wrong.
Common errors
- Writing several tests at once. You lose the signal about which change fixed which test. Add one test per cycle.
- Skipping the run in red. Without seeing the failure, you do not know the test can fail.
- Running only the new test in green. Run the full suite. A change that fixes one test can break another.
- Refactoring while red. You cannot tell whether a failure comes from the old bug or the new structure.
- Letting the agent change the test to match its output. The test is the specification. Changing it changes the requirement.
- Accepting a large diff for a small test. If one test produced many changed lines, the step was too big. Reject it and narrow the request.
Summary of the cycle
| Phase | Your action | Check before moving on |
|---|---|---|
| Red | Write one failing test, run it | Fails with an assertion on the missing behavior |
| Green | Write the smallest passing change, run the full suite | All tests pass, no hardcoded results |
| Refactor | Improve structure, rerun after each step | All tests still pass, no new behavior added |
Exercise
You ask an agent to add a test for slugify handling an empty string. You run it and it passes immediately, before any code change. What should you do, and why?
Show answer
Do not move on. A test that is green before any implementation change means either the behavior already exists (for example, the regex version returns "" for empty input) or the test asserts nothing meaningful. Check which by reading the test and temporarily breaking the code, for example by making slugify return "x", to confirm the test turns red. If the behavior already exists, keep the test as documentation of that behavior but note that it did not drive any code. If the test cannot fail, rewrite it.
Exercise
An agent finishes a green step by writing if text == "Hello, World!": return "hello-world" above the existing code. Which rule in the working agreement does this break, and what is the correct next step?
Show answer
It breaks rule 6, which forbids hardcoding expected values from tests into the implementation. The next step is to reject the change, then add or ask for another test with different inputs, such as "Good Night!" expecting "good-night", so that only a general implementation can pass. Then ask the agent again for the smallest general change.