Sub topic 7
Refactor while the tests stay green
This chapter assumes you can write and run pytest tests, read a Git diff, and have used a coding agent. It covers the third step of the cycle: improving code structure without changing what the code does.
What refactoring means here
Refactoring is changing the structure of code while keeping its observable behavior the same. In TDD it happens only after the tests pass. The passing suite is the safety net: if a change breaks behavior, a test fails and you know at once.
This gives a strict rule. Never refactor on red. If a test is failing, you cannot tell whether a new failure came from the refactor or from the unfinished feature.
Start from the slugify example
After the first cycles, the simple implementation looks like this:
# slugify_util.py after the first cycle
def slugify(text):
return text.lower().replace(" ", "-")Later cycles added tests for punctuation and repeated separators. Patching each case with another replace call would produce tangled code. Once all three tests pass, the code can be restructured. The refactored version below passes the same tests:
# 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)The tests did not change. Only the implementation did. That is the sign of a real refactor.
The refactor loop with an agent
Ask the agent to follow this loop explicitly. A prompt that works well:
- Confirm the suite is green before you start. If it is not, stop.
- Make one structural change, such as extracting a function or renaming a variable.
- Run the full suite after that change, not only the most recent test.
- If anything fails, revert that change instead of editing tests or adding fixes.
The command stays the same as in earlier chapters:
python -m pytest -qRunning the full suite matters because a refactor can break behavior that the current test does not cover.
Common errors
| Error | What happens | Prevention |
|---|---|---|
| Refactoring while a test is red | You cannot tell which change caused a failure | Require a green suite before any refactor |
| Adding behavior during a refactor | A new feature has no failing test behind it | Keep refactors behavior-neutral and add features through a new red step |
| Editing tests to match the new structure | The safety net moves with the code and protects nothing | Tests should need no change unless they call internal names you renamed |
| Large rewrites in one step | A failure has many possible causes | Make one change, run the tests, then continue |
Agents are especially prone to the second error. Asked to "clean up", an agent may also fix an edge case it noticed. That change is not covered by a test, so the suite cannot confirm it.
What the tests cannot tell you
A green suite only proves the behaviors you wrote tests for. The refactored slugify above also changes how non-ASCII text is handled, because the regex drops characters like é. The old version would have kept them. No test covers that, so the suite stays green. Review the diff for changes like this, and add a test first if the behavior matters.
Exercise
An agent is asked to refactor a function and reports "all tests pass". Looking at the diff, you see that one assertion in the test file was also changed. What should you do, and why?
Show answer
Treat the result as unverified. Revert the test change and rerun the suite against the refactored code. A refactor should not require test edits, so the changed assertion may be hiding a behavior change. If the test was wrong, handle that as a separate, explained change.