Sub topic 5
Red: write a failing test and check why it fails
This chapter covers the first step of each TDD cycle: writing one test that fails, and confirming it fails for the right reason. It assumes you can write and run unit tests in Python with pytest, read a Git diff, and have used a coding agent. The examples use a small slugify function, which turns a title into a URL-friendly string.
Why the red step matters more with an agent
In classic TDD the red step is a discipline check. You prove the test can fail before you trust it when it passes. With a coding agent it also does two other jobs:
- It is the specification. The agent can't read your mind. A failing test states in executable form what "done" means for this cycle.
- It is the stopping condition. The agent keeps editing and running until the test passes. If the test is vague, the agent stops at a vague result.
A test that has never been seen failing gives you no evidence that it checks anything. An agent can write a test that passes immediately, then report success. The cheapest defense is to require the failure output to be shown before any implementation is written.
Write one test for one behavior
Pick the smallest behavior you want next. Name the test after the behavior, not the function. Keep it to one logical assertion.
# test_slugify.py
from slugify_util import slugify
def test_lowercases_and_joins_words_with_hyphens():
assert slugify("Hello World") == "hello-world"This test states two things at once: lowercase output and hyphen-joined words. For a first cycle that is acceptable, since both are needed to produce a recognizable slug. Don't add punctuation handling or repeated separators here. Each of those gets its own cycle.
Choose concrete input and expected values that you computed by hand, not by running the code. If the agent derives the expected value from the implementation, the test just repeats whatever the code does.
Run it and read the failure
A failing test is not enough. The test must fail because the behavior is missing. There are three common ways a test can be red.
Failure 1: the module or name does not exist yet
If slugify_util.py does not exist, running the test gives this:
python -m pytest -q==================================== ERRORS ====================================
____________________ ERROR collecting test_slugify.py ____________________
ImportError while importing test module 'test_slugify.py'.
...
E ModuleNotFoundError: No module named 'slugify_util'
=========================== short test summary info ============================
ERROR test_slugify.py
1 error in 0.05sThis is red in the sense that the run is not green. It tells you nothing about behavior, because the test body never ran. Pytest reports it as an error during collection, not a failure. That wording difference is a useful signal.
Failure 2: a typo or setup mistake in the test
from slugify_util import slugfy # typoThis gives ImportError: cannot import name 'slugfy'. The same applies to a missing fixture, a wrong argument count, or a syntax error. The test is broken and says nothing about the code under test.
Failure 3: the assertion fails
This is the red you want. The test runs, calls the function, and the result differs from the expected value. To reach it, create the smallest stub that lets the import succeed and the call run:
# slugify_util.py
def slugify(text):
return ""Now run the test again:
F [100%]
=================================== FAILURES ===================================
_____________ test_lowercases_and_joins_words_with_hyphens _____________
def test_lowercases_and_joins_words_with_hyphens():
> assert slugify("Hello World") == "hello-world"
E AssertionError: assert '' == 'hello-world'
E - hello-world
test_slugify.py:6: AssertionError
=========================== short test summary info ============================
FAILED test_slugify.py::test_lowercases_and_joins_words_with_hyphens
1 failed in 0.05sThe line starting with E is the evidence. The function returned '' and the test expected 'hello-world'. The cause of the failure is exactly the missing behavior, so the test is ready to drive an implementation.
Check three things in the failure output
Before you let the agent implement anything, confirm each of these.
- The test ran. You see an assertion failure, not a collection error or exception from setup.
- The actual value is plausible.
''from a stub is expected. A traceback from deep inside a library suggests a setup problem. - The expected value is what you meant. Read
hello-worldas a requirement. If it is wrong, fix it now. After the implementation exists, it is easy to bend the test toward the code.
If any check fails, fix the test, not the implementation, and run again.
A test that passes on the first run
Suppose the next test is this:
def test_empty_string_returns_empty_string():
assert slugify("") == ""With the stub return "", this test passes immediately. That is not a successful cycle. The test does not describe missing behavior, and it passes only by coincidence with the placeholder. You have three options:
- Discard it, if the behavior is already covered.
- Strengthen it, by choosing input that exposes missing behavior.
- Keep it as a regression guard, but label it that way and don't count it as a TDD step.
Never skip the run. A test you haven't seen fail has not been shown capable of failing.
Specify behavior, not implementation
An agent given a test can satisfy it in many ways, and the test only constrains what it checks. Two habits keep the red step useful.
- Assert on outputs and observable effects. Avoid checking which helper function was called or how many times a regex ran. Those assertions lock in implementation choices and break during refactoring.
- Use varied examples over several cycles. One example is satisfied by a hardcoded return. Later chapters cover how agents exploit that. At the red step, your job is to keep each test pointed at one behavior so the set of tests grows into a real specification.
Here are the next two tests, each added in its own cycle after the first one is green:
# 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"Against the simple implementation from the first cycle (text.lower().replace(" ", "-")), the punctuation test fails with 'hello,-world!' != 'hello-world'. That message points at exactly the missing behavior, so it is a valid red. The repeated-separator test would be written only after the punctuation test is green.
Telling the agent to stop at red
Agents tend to continue past red, writing the implementation in the same turn. State the stopping point explicitly. This instruction fragment can go in the agent's instruction file or in the prompt for the cycle:
## Red step
1. Write exactly one new failing test for the requested behavior.
2. Run `python -m pytest -q` and paste the failure output.
3. State in one sentence why the test fails. It must fail on the assertion, not on an import error, typo, or setup problem.
4. Stop. Do not edit any non-test file until I confirm the failure is the intended one.The pause costs a few seconds and gives you the checkpoint where a bad test is cheapest to fix. Once you trust the agent on simple cycles, you can relax the pause but keep the requirement to show the output.
Handling stubs
Creating a stub to move from an import error to an assertion failure is a normal part of the red step. Keep these rules:
- The stub does the least possible: return an empty value or raise
NotImplementedError. - The stub never contains logic. If it computes anything, you are already in the green step.
- A stub that raises
NotImplementedErrorgives a failure ofNotImplementedErrorinstead of an assertion mismatch. That is acceptable, because it shows the code ran and found nothing implemented. Returning a neutral value gives a clearer diff between actual and expected.
Common errors at the red step
| Symptom | Likely cause | Fix |
|---|---|---|
| `ModuleNotFoundError` on the first run | Implementation file not created, or wrong import path | Create a stub, or fix the path or package layout |
| Test passes before any change | Test duplicates existing behavior, or expected value matches the stub | Change the input to expose missing behavior |
| Failure mentions the wrong function | Test imports a different module than intended | Check the import and the name being called |
| Several tests fail at once | Agent wrote multiple tests in one cycle | Keep one, remove or defer the rest |
| Expected value was copied from the code's output | Test was written after the implementation | Compute the expected value by hand from the requirement |
Exercise
You ask an agent to add a test for slugifying "Rock & Roll" to "rock-roll". It adds the test and runs the suite. The output shows "ERROR collecting test_slugify.py ... ImportError: cannot import name 'slugify'". Is this a valid red? What should happen next?
Show answer
No. The error occurs during collection, so the assertion never ran and nothing is known about the behavior. Likely the function has the wrong name or does not exist yet. Fix the import or add a minimal stub, such as a slugify function that returns an empty string, then run again. Only when the output shows an assertion failure such as assert '' == 'rock-roll' is the red valid.
Exercise
A new test assert slugify("already-a-slug") == "already-a-slug" passes on its first run against the current implementation text.lower().replace(" ", "-"). Should you proceed to the green step? What are your options?
Show answer
There is no green step to do, because the test does not fail. It describes behavior the code already has. Either discard it, keep it as a labeled regression test outside the TDD flow, or change the input so it exposes missing behavior (for example "already--a--slug", which should collapse to "already-a-slug"). Then run again and confirm an assertion failure before any implementation change.