Write tests before the agent writes code · Code Crushers
Lesson 9 of 10 · 75 min
Write tests before the agent writes code
Turn a pricing rule into tests that fail first, let an agent implement against them, and find out whether your tests would have caught a wrong implementation.
Outcome: Write tests from a requirement that fail before the change and catch a wrong implementation of it.
Note
Reading as a visitor
Everything in this lesson is free to read. Sign in and enrol to answer the questions and record your progress.
Derive test cases from a written rule: one per outcome, and one on each side of every boundary.
Confirm that each new test fails before the change, and fails for the reason you expect.
Write tests against the public interface, so that they accept any correct implementation.
Keep an agent from weakening the tests while it makes them pass.
Judge a test suite by the faults it catches, not by whether it is green.
Prerequisites
Reading and writing TypeScript, including async and await.
Has written or read tests with node:test or a similar test runner.
HTTP basics: methods, status codes and JSON bodies.
Running commands in a terminal.
Concepts
Why the order matters with an agent
An agent asked for "the feature, with tests" usually writes the code first and the tests second. Tests written that way describe what the code does. If the code gives a 4-hour booking no discount, the test asserts no discount, and everything is green. The tests agree with the code because they were derived from it, so they cannot tell you whether the code agrees with the requirement.
Writing the tests first reverses the dependency. The tests come from the requirement, the code has to satisfy them, and a mistake in the code shows up as a failure instead of being copied into an assertion. It also gives the agent something it works well with: a concrete target it can run. "Make these tests pass without changing them" is a far tighter instruction than a paragraph of prose.
From a rule to test cases
Read the requirement as a table of outcomes, then add the cases the table implies but does not list:
One case per outcome. For a tiered rule, one case inside each tier.
Two cases per boundary. Words such as "at least", "up to", "before" and "more than" differ only at the exact boundary value. Put one case on the boundary and one on the nearest value below it that the system allows. A test in the middle of a tier cannot tell >= from >.
One case per "not". If the rule says the discount is on the whole price, not only on the extra hours, pick a length where those two readings give different prices and assert the right one.
Something that must not change. The cheapest regression test for a pricing change is a short booking that still costs what it did.
Assert exact values taken from the requirement, not values computed in the test by the same formula as the code. assert.equal(price, 21600) can be checked against the request by anyone. repeats the implementation and repeats its mistakes.
Worked example
This walk-through takes a different pricing rule through the steps you will use in the exercise: cases from the rule, tests that fail first, an agent that implements against them, and a check of the tests themselves. It is an illustration only. You do not need to build it, and it is not assessed.
The requirement
A single booking never costs more than 200000 cents. A booking whose price pro rata would be higher is charged exactly 200000. Cheaper bookings are priced as today.
1. List the cases
Only the Table Mountain meeting room (30000 cents per hour, 30-minute slots, open 08:00 to 18:00 in Johannesburg) can reach the cap, so the cases use it. Its opening hours are 06:00 to 16:00 UTC.
Booking
Price pro rata
Expected price_cents
Why this case
1 hour
30000
30000
Something that must not change
6 hours 30 minutes
195000
195000
The longest booking below the cap
7 hours
210000
200000
Concept questions
Sign in and enrol to answer and save your progress.
Exercise
Your task
Your workspace holds the booking service described in README.md, and a request from the operations lead in docs/discount-request.md: longer bookings should be cheaper.
Length of the booking
Price
Less than 4 hours
The hourly rate pro rata, as today
At least 4 hours, less than 8 hours
10% off the whole price
At least 8 hours
25% off the whole price
Read the request in full before you start: it settles what "at least" means, which price the discount applies to and where the price shows.
Write the tests first, then have the rule implemented against them. Both are assessed: the service's prices, and how well your tests tell a correct implementation from a wrong one.
Steps
Read the request and the existing tests.test/bookings.test.ts shows how tests book through app.inject(), and test/helpers.ts has the fixtures: (6000 cents per hour, 60-minute slots, open all day), (12000 cents per hour, 15-minute slots) and (30000 cents per hour, 30-minute slots), and for times.
Reflection
Recorded for you to look back on. It is not graded and does not by itself show understanding.
Prompt: Which of your tests failed first for a reason you did not intend, and what did you change? If you used an agent to implement the rule, did it try to change a test, or pass the tests in a way the requirement did not mean? Name one fault your tests would still miss.
Run the new tests before any implementation exists. Each one should fail, and the failure message should be the one you expect: 24000 !== 21600, the full price where the discounted one belongs. Two other results are warnings:
The test passes. It does not depend on the new behaviour. Either the assertion is too weak or it tests something that already works.
The test fails for another reason. A 400 because the booking is outside opening hours, a 409 because two test bookings overlap, a typo in an import. Such a test will keep failing after a correct implementation, or start passing for the wrong reason once the unrelated problem is fixed.
A test you have never seen fail has not shown that it can.
Test the interface, not the implementation
Decide what the tests are allowed to know. Tests that call POST /bookings and read price_cents know only the contract in the requirement, so any correct implementation passes them, including one an agent structures differently from how you would. Tests that import a helper such as discountPercent from src/ also fix its name, its file and its signature. They break when the code is reorganised, and they make the agent's job "match this internal design" rather than "meet the requirement".
Unit tests of internals have their place, but write them after the design exists. The tests that come first should be the ones that stay true however the feature is built.
Hand the tests to the agent
Give the agent the requirement, the failing tests and explicit limits:
make the failing tests pass by changing src/ only;
do not edit, skip or delete tests, and do not change the test helpers;
if a test looks wrong, stop and say why instead of changing it.
Then check that the limits held. Look at the diff of test/ first: an agent under pressure to turn a run green may loosen an assertion, wrap it in a condition, or mark a test as skipped. Look for code that special-cases the exact inputs your tests use. Run the tests yourself rather than accepting a report that they pass.
Sometimes the agent is right that a test is wrong, because your expected value was miscalculated. That is a finding about the test, and you fix it by going back to the requirement, not by accepting whatever the code returns.
Would your tests catch a wrong implementation?
Green tests prove that the code passes these tests. Whether the tests are any good is a separate question, and you can answer it the same way you tested the code: break the implementation on purpose and see whether a test fails.
Change >= to > at one boundary.
Change a percentage.
Apply the discount to part of the price.
Remove the rule altogether.
Each of these should turn at least one test red. A change that leaves everything green shows a gap: write the missing test, watch it fail against the broken code, then restore the code. This is mutation testing done by hand, and a few minutes of it tells you more about a test suite than its size or its coverage figure.
The exercise assesses your tests this way. They are run against a correct implementation that is not yours, against the unchanged starting point, and against several implementations that are each wrong in one specific way.
The shortest booking above the cap
10 hours
300000
200000
Far above: the cap is a ceiling, not a deduction
With 30-minute slots no booking costs exactly 200000 pro rata, so the two cases around the cap are the nearest ones on each side. The last row exists because of a plausible misreading: "subtract the 10000 by which 7 hours exceeds the cap" would pass the 7-hour case by coincidence if it were implemented as a fixed deduction.
2. Write the tests against the API
import assert from "node:assert/strict";
import { describe, it } from "node:test";
import { ADA, auth, futureUtc, JOHANNESBURG_ROOM, useTestApp } from "./helpers.ts";
describe("price cap", () => {
const { app } = useTestApp();
/** Books the room from 06:00 UTC (08:00 local) for the given number of minutes and returns the price. */
async function roomPrice(minutes: number): Promise<number> {
const response = await app().inject({
method: "POST",
url: "/bookings",
headers: auth(ADA),
payload: {
resource_id: JOHANNESBURG_ROOM,
starts_at: futureUtc(6),
ends_at: futureUtc(6 + Math.floor(minutes / 60), minutes % 60),
},
});
assert.equal(response.statusCode, 201, response.body);
return response.json().data.price_cents;
}
it("leaves a booking below the cap unchanged", async () => {
assert.equal(await roomPrice(60), 30000);
assert.equal(await roomPrice(390), 195000);
});
it("charges exactly the cap above it", async () => {
assert.equal(await roomPrice(420), 200000);
assert.equal(await roomPrice(600), 200000);
});
});
Two details are deliberate. The helper asserts the 201 and prints the response body when it is something else, so a refused booking fails with its error code instead of with a confusing undefined !== 30000. And the expected values are literals from the table, not Math.min(…) in the test.
3. Run them and read the failures
npm test before any change:
✖ leaves a booking below the cap unchanged
POST /bookings … 409 SLOT_UNAVAILABLE
✖ charges exactly the cap above it
210000 !== 200000
The second failure is the right one: the full price where the cap belongs. The first is not. The two bookings in one test overlap, because both start at 06:00 on the same day, and the test database is only reset between tests. That test would have kept failing after a correct implementation. The fix is in the test: give roomPrice a day argument and book each case on its own day. After that the first test passes, which is correct, because it describes behaviour that already exists and must be kept. The second still fails with 210000 !== 200000.
4. Hand over to the agent
The prompt, in full:
Read docs/price-cap-request.md and test/price-cap.test.ts. Make the failing test pass by changing files under src/ only. Do not edit, skip or delete any test or test/helpers.ts. If you think a test is wrong, stop and tell me why. Run npm run verify when you are done and show me the output.
Before reading that, check the limits held: git status shows only src/rules.ts modified, and git diff test/ is empty. Then run npm run verify yourself.
5. Test the tests
Break the implementation in ways a hurried author might, one at a time, and run the tests after each:
Change to priceCents
Result
Remove the Math.min
210000 !== 200000: caught
Cap at 210_000 instead
210000 !== 200000: caught
Deduct a fixed 10000 from prices above the cap
290000 !== 200000 at 10 hours: caught, by the last row of the table only
Apply the cap only when resource.id === 1
Nothing fails
The last line is a gap. Every capped case books the meeting room, and no other fixture resource can reach the cap: twelve hours on the Hudson focus booth cost 144000. So the tests cannot tell "no booking costs more than 200000" from "no booking of the meeting room costs more than 200000", and the second would be wrong the day a more expensive resource is added. The remedy is a test that inserts its own resource with a high hourly rate, using the database handle that useTestApp() also returns, and asserts the cap on it. Finding that out took four small edits and four test runs.
LAB
NEW_YORK_BOOTH
JOHANNESBURG_ROOM
futureUtc(hour, minute, daysAhead)
List your cases. One per row of the table, two per boundary (exactly on it and just below), and one for each thing the request rules out. Take the expected prices from the examples in the request, or work them out by hand.
Write the tests in a new file under test/, for example test/discount.test.ts. Make every request through the HTTP API and assert exact price_cents values. Book each case on its own day, or on times that do not overlap: the test database is reset between tests, not within one.
Run them and read every failure.npm test should show your new tests failing because the price is the full price. A new test that passes already, or fails with a 400 or 409, needs fixing before you go on. The existing tests must stay green.
Implement the rule. If you use an agent, give it the request and your tests, and tell it to change src/ only, not to edit, skip or delete tests, and to stop and explain if it thinks a test is wrong. Afterwards check the diff of test/ before anything else.
Verify. Run npm run verify (type check and all tests). Then try it by hand:
Eight hours on the lab cost 48000 at the full rate, so price_cents should be 36000.
Test your tests. Break priceCents on purpose, one change at a time: > instead of >= at 4 hours, the same at 8 hours, 10% for the top tier, a discount on short bookings, a discount on the extra hours only. Run npm test after each. Every change should make at least one test fail. Where nothing fails, add the missing test, then restore the code.
Constraints
Do not change package.json or package-lock.json, and do not add dependencies. A submission whose lockfile differs is not assessed.
Keep your tests in test/, in files named *.test.ts, runnable with npm test. Keep test/helpers.ts working with the starting point's src/app.ts and src/db.ts.
Tests may use what the starting point's src/ exports and the database handle from useTestApp(). They must not depend on anything you add to src/.
Do not edit db/migrations/001_init.sql. This change needs no schema change.
Keep every existing endpoint and response working as documented.
How Check work assesses this
Check work takes a snapshot of your workspace's source files and assesses it outside the lab, in two parts.
Your service is started with node src/server.ts against a fresh database and called over HTTP. Bookings of many lengths, on several resources, must cost what the request says, and the existing behaviour must be unchanged.
Your tests are run with the same command as npm test, several times, each time against a different implementation of the booking service in place of your src/:
a correct implementation of the discount that is not yours: your tests must pass;
the unchanged starting point, with no discount: your tests must fail;
five implementations that are each wrong in one way (a boundary at 4 hours, a boundary at 8 hours, the size of the top discount, a discount on short bookings, a discount on only part of the price): your tests must fail against each.
Only whether a run passes or fails is used; nothing your tests print is read. If your tests do not pass against the correct implementation, the remaining runs are skipped, because a failure against a faulty implementation proves nothing unless the same tests accept a correct one. Each run has 30 seconds.
Not assessed: the order in which you wrote things, rounding, the readability of your tests, and faults other than those five. Your reflection is recorded but not graded.
Tools
You can do this exercise with Claude Code, OpenCode, Codex CLI or OpenHands in the lab. Write the list of cases yourself, even if an agent then types the tests: deciding what to assert is the part of this exercise that cannot be delegated.
Acceptance criteria
AC1Bookings shorter than 4 hours keep the full price.Verified behaviour
AC2Bookings of at least 4 and less than 8 hours get 10% off the whole price.Verified behaviour
AC3Bookings of at least 8 hours get 25% off the whole price.Verified behaviour
AC4Existing booking behaviour still works.Verified behaviour
AC5Your tests pass when run against a correct implementation of the discount that is not yours.Verified behaviour
AC6Your tests fail when run against the starting point, which has no discount.Verified behaviour
AC7Your tests fail against implementations with a wrong boundary at exactly 4 hours or exactly 8 hours.Verified behaviour
AC8Your tests fail against implementations that discount the wrong amount or the wrong bookings.Verified behaviour
Verified behaviour is checked by running your submitted work from outside the lab. A structure check confirms that something is present and in the expected format; it does not prove it is correct.
Not assessed
The order in which you wrote tests and code: the assessment sees only the files you submit.
Rounding: the faulty implementations your tests are run against all round correctly.
The readability and structure of your tests and code.
Faults other than the five the assessment uses. Tests that catch those five can still miss others.
Your reflection: it is recorded, not graded.
Hints
Try the exercise first. Each hint gives away a little more than the one before.
Check your work
Submit your work from the lab's Check work panel. Hidden checks run your submitted code from outside the lab; your own test output is never taken as a result. You can revise and resubmit.