Sub topic 7
Turning acceptance criteria into tests
This chapter assumes you can write and run pytest tests, use Git, and have prompted a coding agent before. It covers how to turn the acceptance criteria from a requirement into automated tests. An agent's output can then be checked by running those tests instead of by reading the code.
Why tests are the executable form of a spec
A requirements document is prose. An agent can read it, but it can also misread it, and so can you. A test is the same statement written so that a machine can say yes or no.
Consider what happens without tests. The agent reports "task done." You read the diff, decide it looks reasonable, and merge. You have checked the agent's explanation of the code, which is not the same as checking the behavior. With tests derived from the criteria, the check becomes: run the suite and see whether each criterion passes.
This is why the spine places executable verification downstream of both requirements and tasks. Requirements say what must be true. Tasks say what to build next. Tests connect them, because each task names the criteria it covers and each criterion has a test.
Anatomy of a testable criterion
The EARS-style pattern from the requirements chapter gives each criterion a trigger, a condition, and a response. Those three parts map directly onto the three parts of a test.
| Criterion part | Keyword | Test part |
|---|---|---|
| Trigger or precondition | WHEN, IF | Arrange and act: set up state, call the code |
| Response | SHALL | Assert: check the observable result |
| Boundary values in the text | "30 minutes", "same response" | Parametrized cases at and around the boundary |
Take criterion 1 from the password reset requirement:
- WHEN a user submits a registered email address THEN the system SHALL send a reset link that expires after 30 minutes.
The number 30 is the useful part. It tells you where to put test cases: just inside the limit and just outside it. A criterion with no concrete value, such as "expires quickly", cannot be turned into a test until someone picks a number. If you cannot write the assertion, the criterion is not finished. Fix the requirement, not the test.
A worked example
The following tests encode criteria 1 and 3. The tiny ResetTokens class is included so the file runs on its own. In a real project it would live under src/ and the tests would import it.
from datetime import datetime, timedelta, timezone
import pytest
TOKEN_TTL = timedelta(minutes=30)
class TokenError(Exception):
pass
class ResetTokens:
def __init__(self):
self._issued = {}
self._used = set()
def issue(self, token, now):
self._issued[token] = now
def redeem(self, token, now):
if token in self._used:
raise TokenError("already used")
issued = self._issued.get(token)
if issued is None or now - issued > TOKEN_TTL:
raise TokenError("expired or unknown")
self._used.add(token)
T0 = datetime(2026, 1, 1, tzinfo=timezone.utc)
def test_token_expires_after_30_minutes():
tokens = ResetTokens()
tokens.issue("abc", T0)
tokens.redeem("abc", T0 + timedelta(minutes=29)) # still valid
tokens.issue("def", T0)
with pytest.raises(TokenError):
tokens.redeem("def", T0 + timedelta(minutes=31))
def test_token_can_be_used_only_once():
tokens = ResetTokens()
tokens.issue("abc", T0)
tokens.redeem("abc", T0)
with pytest.raises(TokenError):
tokens.redeem("abc", T0)Three design choices in this file are worth copying.
- Time is a parameter.
redeemtakesnowinstead of reading the clock. The test controls time exactly, so it never sleeps and never flakes. If your code reads the clock internally, inject a clock object or use a time-freezing library. - Each test names its criterion. The first test is named for the 30-minute rule. The second is named for single use. When one fails, the name tells you which requirement broke.
- Failures are asserted by type.
pytest.raises(TokenError)checks that the code rejects the input in the intended way. A bareExceptionwould also pass if the code crashed for an unrelated reason.
Tracing tests back to criteria
A test suite that grows without structure loses the link to the spec. Keep the link visible so reviewers, and the agent, can see which criterion each test covers.
Two lightweight ways to do this:
- Put the criterion ID in the test name or docstring, for example
test_req1_3_used_link_rejected. - Use a custom pytest marker, such as
@pytest.mark.criterion("1.3"), and register it inpytest.iniso pytest does not warn about unknown markers.
Then add a coverage check to your review: every criterion in the requirements file has at least one test, and every test points to a criterion. Tests without a criterion are not wrong, but they are a sign that behavior exists that the spec does not describe.
Boundary and edge cases the criteria imply
The example above leaves out cases that a thorough suite would include. Reading each criterion for what it implies helps you find them.
- Exact boundary. The code uses
>so a token redeemed at exactly 30 minutes is still valid. The criterion says "expires after 30 minutes", which is ambiguous at that instant. Write a test for exactly 30 minutes. If the test forces a decision, record it in the spec instead of leaving it in the code. - Unknown tokens. The implementation treats unknown and expired tokens the same. Decide whether that is intended and test it.
- Failed redemption and the used flag. In the sample code a rejected expired token is not marked used. Whether that matters is a design decision.
- Criterion 2 is a negative property. "Return the same response for registered and unregistered addresses" is about what an attacker cannot learn. Test that the status code, body, and ideally the response shape are identical for both inputs. Timing differences are a real leak too, and a unit test usually cannot see them. Note that gap in the design document.
Writing tests before the agent writes code
The task list in this tutorial says "Write tests first" for token redemption. That order is deliberate, and it matters more with an agent than with a person.
If the agent writes the code first and then the tests, the tests tend to describe what the code does, not what the requirement says. Bugs pass because the test was written to match them. If the tests exist first, they are fixed points that come from the spec.
A workable sequence for one task:
- Write or review the tests for the criteria the task covers. Confirm the tests fail for the right reason, for example a missing function, not a typo.
- Give the agent the task, the criteria, and the instruction not to edit the tests.
- The agent implements until the tests pass.
- Run the full suite, not only the new tests, to catch regressions.
- Review the diff.
Step 1 is easy to skip and costly to omit. A test that has never failed has not been shown to check anything.
Who writes the tests
You have three options, and they differ in how much independence the tests keep from the implementation.
| Approach | Strength | Risk |
|---|---|---|
| You write the tests | Strongest link to your intent | Slower, and you must know the test framework |
| Agent writes tests from the criteria, you review them, then a fresh agent session implements | Fast, and the tests do not depend on the implementation | Needs careful review of the tests |
| Agent writes tests and code in the same session | Fastest | Tests tend to mirror the code, so they prove less |
The middle option is a good default. Reviewing ten assertions against a criterion is much cheaper than reviewing the whole implementation.
What tests cannot check
Passing tests show that the encoded criteria hold. They say nothing about behavior nobody encoded.
- Missing criteria. If the requirement omits rate limiting, no test will ask for it.
- Weak assertions. A test that only checks "no exception was raised" passes for many wrong implementations.
- Mocks that hide the real behavior. If the test replaces the email sender with a stub, it checks that the code calls the stub, not that an email arrives. Keep at least one integration test for each criterion that depends on an external system.
- Non-functional requirements. Security, performance, and accessibility need their own checks, or a human review step.
Because of these gaps, the tests narrow what a reviewer has to read, but they do not replace the review. The next chapters on review gates and spec drift cover what to look at after the suite is green.
Making the check easy for the agent to run
An agent can only use tests as feedback if it can run them with one command and read the result. Put that command in the project instruction file so it is stated once:
## Verification
- Run `pytest -q` before reporting a task as done.
- Report the number of tests passed and failed.
- Do not edit files under `tests/` unless the task says to.Keep the suite fast. If it takes ten minutes, the agent will skip it or you will stop waiting for it. Separate quick unit tests from slower integration tests with markers, and run the quick set after each task and the full set before merge.
Common mistakes
- Writing one big test per requirement. When it fails you cannot tell which criterion broke. Write one test per criterion, at minimum.
- Asserting implementation details. Checking that a private method was called makes refactoring break tests without any behavior change. Assert on outputs and observable effects.
- Using the real clock, network, or random values. These make results vary between runs. Inject them.
- Letting the agent mark criteria as covered. Check the coverage yourself with the criterion-to-test list.
- Treating a green suite as approval. Green means the encoded criteria hold. It does not mean the spec was complete.
Exercise
Criterion: "WHEN a user requests a password reset more than 5 times in one hour THEN the system SHALL reject the request." List the test cases you would write, and name one thing in the criterion you would clarify in the spec first.
Show answer
Test cases: 5 requests in one hour are all accepted; the 6th request within the hour is rejected; a request made after the hour window has passed is accepted again; requests from two different users do not count against each other. Pass the current time as a parameter so the tests do not sleep. Clarify first: whether the hour is a fixed window or a sliding window, what "reject" means (status code and message), and whether the limit is counted per account or per IP address. Without those decisions the boundary tests cannot be written.
Exercise
An agent's diff makes a failing test pass, but it also changes assert result == 403 to assert result in (200, 403) in an existing test. What should you do, and why?
Show answer
Treat the test change as a spec change and reject it unless the requirement itself changed. The weakened assertion lets the implementation return 200 where the spec requires 403, so the suite no longer checks the criterion. Restore the original assertion, ask the agent to fix the implementation instead, and add "do not modify existing tests" to the project instruction file.