Writing tests that prove something
Once a team adopts coding assistance and shared repository instructions, test volume usually rises fast. A single prompt produces a feature, twenty unit tests, and a green CI run. Review gets slower rather than safer: the pull request carries hundreds of lines of test code, yet nobody is sure which bugs those tests would actually catch.
The problem is structural. When the same session writes both the implementation and the tests—or reads existing code to backfill coverage—the tests tend to describe what the code happens to do rather than what the business requires. Changing how the team writes and reviews AI-assisted tests means moving the specification ahead of the implementation and treating the test suite as an independent check rather than an automatic companion to the diff.
Tests that mirror the code #
Move away from background workers to an everyday domain problem: invoice calculation in a subscription billing service. Suppose product and finance maintain a short specification in docs/billing-rules.md:
- Line items are priced in integer cents (
unitPriceCents * quantity) and markeddiscountable: trueorfalse(setup fees and gift cards are non-discountable). - A percentage coupon applies only when the discountable subtotal is at least
minSubtotalCents, reducing only the discountable portion (rounded to the nearest cent withMath.round). - Fixed account credit is subtracted after the percentage coupon and reduces the remaining invoice balance down to a floor of
0.
Ask a coding assistant in one shot to implement calculateInvoice and add unit tests, and a plausible first pass can look like this:
// src/billing/calculate-invoice.ts
export interface LineItem {
sku: string;
unitPriceCents: number;
quantity: number;
discountable: boolean;
}
export interface Coupon {
code: string;
percentOff: number;
minSubtotalCents: number;
}
export interface InvoiceInput {
items: LineItem[];
coupon?: Coupon;
accountCreditCents: number;
}
export interface InvoiceSummary {
subtotalCents: number;
couponDiscountCents: number;
appliedCreditCents: number;
totalCents: number;
}
export function calculateInvoice(input: InvoiceInput): InvoiceSummary {
const subtotalCents = input.items.reduce(
(sum, item) => sum + item.unitPriceCents * item.quantity,
0,
);
const discountableCents = input.items
.filter((item) => item.discountable)
.reduce((sum, item) => sum + item.unitPriceCents * item.quantity, 0);
const appliedCreditCents = Math.min(subtotalCents, input.accountCreditCents);
const couponBase = Math.max(0, discountableCents - appliedCreditCents);
const couponDiscountCents =
input.coupon && subtotalCents >= input.coupon.minSubtotalCents
? Math.round((couponBase * input.coupon.percentOff) / 100)
: 0;
return {
subtotalCents,
couponDiscountCents,
appliedCreditCents,
totalCents: Math.max(0, subtotalCents - appliedCreditCents - couponDiscountCents),
};
}
The function compiles cleanly and hides two real billing defects. First, it checks minSubtotalCents against subtotalCents instead of discountableCents, so a non-discountable setup fee unlocks a percentage coupon. Second, it subtracts appliedCreditCents from discountableCents before taking the percentage discount, shrinking the coupon and overcharging customers who combine a coupon with account credit.
Now consider the tests an assistant typically generates alongside that function:
// Weak tests: 100% line coverage, zero protection against either defect.
const withCoupon = calculateInvoice({
items: [{ sku: "seat", unitPriceCents: 6000, quantity: 2, discountable: true }],
coupon: { code: "SAVE20", percentOff: 20, minSubtotalCents: 12000 },
accountCreditCents: 0,
});
assert(withCoupon.couponDiscountCents === 2400 && withCoupon.totalCents === 9600);
const creditFloor = calculateInvoice({
items: [{ sku: "seat", unitPriceCents: 2000, quantity: 1, discountable: true }],
accountCreditCents: 3500,
});
assert(creditFloor.appliedCreditCents === 2000 && creditFloor.totalCents === 0);
Those two tests execute every line and branch of calculateInvoice and pass cleanly. Worse, if the engineer asks the assistant to add a mixed-item test after reading the implementation, the assistant will often run the function or trace its formula and assert couponDiscountCents === 2000 or 2100—locking the two defects into the regression suite as expected behaviour.
Anchoring tests to an outside spec #
Breaking that circular agreement requires separating test authoring from implementation—the same independence principle behind review-and-critique loops, where the evaluator must draw its criteria from outside the generator's own draft.
In daily work, the engineer splits the interaction into two explicit steps:
- Specification to failing tests. Give the assistant
docs/billing-rules.md, the public types (InvoiceInput,InvoiceSummary), and worked examples verified by the engineer or product owner—before asking it to editcalculate-invoice.ts. Run the new tests first and confirm they fail for the right reasons. - Implementation under fixed assertions. Instruct the assistant to make the failing suite pass without modifying or weakening the specification assertions.
For the billing rules above, a specification-driven prompt looks like this:
Read
docs/billing-rules.mdand the public types insrc/billing/calculate-invoice.ts. Write tests intest/calculate-invoice.test.tscovering: (1) a $100 discountable seat subtotal plus a $50 non-discountable setup fee with a 20% / $120-minimum coupon must yield0coupon discount; (2) a $120 discountable subtotal plus a $50 setup fee with the same coupon and $15 account credit must apply the $24 coupon before the $15 credit for a $131 total; (3) excess credit floors the total at0. Run the tests and report failures before editing production code.
Running those checks against the buggy implementation above (along with an invariance check described below) produces three concrete failures:
non-discountable-threshold: expected 0 discount, got 2000
coupon-before-credit-at-threshold: expected 2400 discount, got 2100
non-discountable-invariance: coupon changed from 0 to 1900
That failure output gives the assistant an unambiguous target—and gives the reviewer proof that the tests actually reject the broken behaviour rather than merely describing whatever code was written first.
Behaviour and invariants over mock choreography #
AI assistants also default to mocking internal helpers when asked to test a module in isolation. A test that replaces calculateCouponDiscount with a spy and asserts calledWith(12000, 20) breaks every time someone refactors internal structure while failing to notice when the caller passes the wrong subtotal or subtracts credit in the wrong order.
Testing through the public function—and pairing worked examples with domain invariants—avoids that fragility. The checks below exercise calculateInvoice directly through its public contract (test-runner boilerplate omitted):
// test/calculate-invoice.test.ts
import { calculateInvoice, type InvoiceInput } from "../src/billing/calculate-invoice.ts";
function assert(condition: boolean, message: string): asserts condition {
if (!condition) throw new Error(message);
}
// 1. Non-discountable fees must not unlock a coupon's minimum subtotal.
const belowThreshold = calculateInvoice({
items: [
{ sku: "seat", unitPriceCents: 5000, quantity: 2, discountable: true },
{ sku: "setup", unitPriceCents: 5000, quantity: 1, discountable: false },
],
coupon: { code: "SAVE20", percentOff: 20, minSubtotalCents: 12000 },
accountCreditCents: 0,
});
assert(belowThreshold.couponDiscountCents === 0, "Setup fee unlocked coupon");
assert(belowThreshold.totalCents === 15000, "Total changed unexpectedly");
// 2. Percentage coupon applies at exact threshold before fixed account credit.
const combined = calculateInvoice({
items: [
{ sku: "seat", unitPriceCents: 4000, quantity: 3, discountable: true },
{ sku: "setup", unitPriceCents: 5000, quantity: 1, discountable: false },
],
coupon: { code: "SAVE20", percentOff: 20, minSubtotalCents: 12000 },
accountCreditCents: 1500,
});
assert(combined.couponDiscountCents === 2400, "Coupon must apply before credit");
assert(combined.appliedCreditCents === 1500, "Full credit should apply");
assert(combined.totalCents === 13100, "Unexpected combined total");
// 3. Excess credit caps at the remaining balance; total never drops below zero.
const floored = calculateInvoice({
items: [{ sku: "seat", unitPriceCents: 2000, quantity: 1, discountable: true }],
accountCreditCents: 3500,
});
assert(floored.appliedCreditCents === 2000, "Applied credit exceeded balance");
assert(floored.totalCents === 0, "Total dropped below zero");
// 4. Invariant: adding a non-discountable item never changes couponDiscountCents.
const base: InvoiceInput = {
items: [{ sku: "seat", unitPriceCents: 5000, quantity: 2, discountable: true }],
coupon: { code: "SAVE20", percentOff: 20, minSubtotalCents: 12000 },
accountCreditCents: 500,
};
const withSetupFee: InvoiceInput = {
...base,
items: [
...base.items,
{ sku: "setup", unitPriceCents: 5000, quantity: 1, discountable: false },
],
};
assert(
calculateInvoice(base).couponDiscountCents ===
calculateInvoice(withSetupFee).couponDiscountCents,
"Non-discountable item altered coupon discount",
);
Notice the fourth check. Instead of hard-coding another hand-calculated number, it states a rule from the specification directly: adding a non-discountable line item must never change couponDiscountCents. Invariant checks are especially effective with coding assistants because they do not depend on a single magic example and survive internal refactoring completely.
Fixing the two lines in calculateInvoice—evaluating minSubtotalCents against discountableCents, computing the coupon on discountableCents, and applying accountCreditCents to the post-coupon remainder—turns all four checks green:
- const appliedCreditCents = Math.min(subtotalCents, input.accountCreditCents);
- const couponBase = Math.max(0, discountableCents - appliedCreditCents);
- const couponDiscountCents =
- input.coupon && subtotalCents >= input.coupon.minSubtotalCents
- ? Math.round((couponBase * input.coupon.percentOff) / 100)
- : 0;
+ const couponDiscountCents =
+ input.coupon && discountableCents >= input.coupon.minSubtotalCents
+ ? Math.round((discountableCents * input.coupon.percentOff) / 100)
+ : 0;
+
+ const afterCoupon = subtotalCents - couponDiscountCents;
+ const appliedCreditCents = Math.min(afterCoupon, Math.max(0, input.accountCreditCents));
return {
subtotalCents,
couponDiscountCents,
appliedCreditCents,
- totalCents: Math.max(0, subtotalCents - appliedCreditCents - couponDiscountCents),
+ totalCents: afterCoupon - appliedCreditCents,
};
Building on the mutation check habit from earlier, the engineer can also flip >= to > on minSubtotalCents or drop the Math.max(0, ...) guard on negative credit input. The exact-threshold check (12000 === 12000) immediately catches >= → >, while a negative-credit mutation exposes a case the suite does not yet cover—prompting one more targeted test rather than a blanket request for "more edge cases."
Changing how the team writes and reviews tests #
Introducing this habit changes three concrete parts of the team's workflow:
Reviewing tests before the implementation. When a pull request adds AI-assisted tests, reviewers open the test file first and read the inputs and assertions against the ticket or specification. Red flags stand out quickly: tests that compute expected values by duplicating production formulas, tests whose mocks assert private helper call counts instead of outcomes, and tests that only exercise inputs where every branch collapses to the same number.
Encoding test rules in AGENTS.md. A short testing section in repository guidance prevents the most common failure modes across every developer's sessions:
## Testing
- Write failing tests from the issue or spec before changing implementation when behaviour is specified.
- Test through public module boundaries and real in-memory data rather than mocking internal helpers.
- Never weaken or rewrite a specification assertion to match unexpected implementation output without raising the discrepancy.
That last rule matters in practice: when an assistant hits a failing test while editing implementation code, its default instinct is often to "fix" the test so the suite turns green. Making assertion preservation explicit gives both the developer and the reviewer a clear line to enforce.
Knowing when test-first is the wrong tool. Specification-driven testing pays off when business rules, API contracts, or bug reproductions are clear—pricing, permissions, parsers, state transitions, and regressions. It slows teams down during exploratory spikes or early UI prototyping where the desired contract is still shifting every hour. In those cases, keeping generated tests disposable until the design settles avoids maintaining brittle assertions for behaviour the team is about to throw away.