Sub topic 2
Red: Write a Failing Test and Check Why It Fails
Assume you know basic Python, can run pytest, understand Git diffs, and have used a coding agent. The goal is to make each behavior explicit before implementation.
Red: Specify One Behavior
Start with one test that describes the required result:
# test_slugify.py
from slugify_util import slugify
def test_lowercases_and_joins_words_with_hyphens():
assert slugify("Hello World") == "hello-world"A test is an executable specification: it states behavior that the program must provide. Run it before asking the agent to implement the behavior:
python -m pytest -qA useful failure points to the missing behavior. For example, this stub produces an intentional failure:
# slugify_util.py
def slugify(text):
raise NotImplementedErrorThe failure should be NotImplementedError, not a missing import, syntax error, or test typo. Check the failure yourself. Then give the agent the test and the exact failure output.
Green: Make the Smallest Change
Tell the agent to implement only the behavior required by the failing test:
> Make the smallest production-code change that makes the new test pass. Do not change the test. Run the full test suite and report its output.
The first implementation can be deliberately narrow:
# slugify_util.py
def slugify(text):
return text.lower().replace(" ", "-")The agent then runs the test command again. Green means the stated behavior passes. It does not mean every possible input is handled.
Refactor While Tests Stay Green
After a passing test, improve structure only if the change preserves behavior. Add another test before expanding the implementation:
def test_strips_punctuation():
assert slugify("Hello, World!") == "hello-world"A later refactor can handle both cases:
import re
def slugify(text):
words = re.findall(r"[a-z0-9]+", text.lower())
return "-".join(words)Run the complete suite after the refactor. The tests are the safety net, not proof that the design is perfect.
Keep Each Cycle Small
One behavior per cycle makes failures easy to diagnose:
- Write one test.
- Confirm its intended failure.
- Ask the agent for the smallest passing change.
- Run the full suite.
- Refactor only while green.
- Review and commit the diff.
Exercise
Why should you verify that a failing test fails for the intended reason before asking an agent to code?
Show answer
Otherwise the agent may respond to an import, syntax, or test error instead of implementing the missing behavior.