Tests as Contracts for AI Coding Agents in Production
Tests are the specification an AI coding agent can execute. Real import and audio-app examples show how narrow contracts make generated code stay honest.
A failed import must never move the saved cursor. That was the core rule in a Rails system I built to import a property inventory platform's history from a third-party API, where an importer pages root records, fetches dependent data, stores raw snapshots, and projects local rows.
If the job advances its cursor after selecting a root and then hits a 429, a bad attachment, or an unexpected payload, the job logs green while a property and its reports, contacts, images, and invoices vanish silently. Writing a failed-root test that asserts the cursor stays put gives an AI coding agent an executable specification, leaving far less room to guess than telling it to "make the import resumable".
The agent only knows what the contract makes observable
A coding agent reads the repository, the prompt, and its command output, and fills in every unwritten assumption in seconds. "Resume imports after a failure" hides half a dozen product choices: whether to resume at the same root or the next page, when to persist the cursor, whether a missing optional endpoint fails the root, and what happens when a live webhook updates a record mid-import. Several implementations can pass a happy-path test while quietly corrupting data.
I still state constraints in the prompt, yet prose gets interpreted while a test runs. I don't ask an agent to "make this safer" or "handle edge cases"; I ask it to make a named rule pass, then read the diff next to the test.
A persisted cursor is a small piece of business policy
At scale, "we'll just run it again" isn't a recovery plan: the property platform holds over 25,000 properties, more than 60,000 inspections, nearly 7 million observations, over 17 million attachments, and more than 4 TB of media. The selector pages properties and inspections in batches of 50 and tracks the current page, offset, and exhaustion flag, locked down by four recovery tests:
- a persisted cursor resumes selection at the exact root after a process restart
- roots already synchronised locally are skipped without blocking later work
- a failed root leaves the persisted cursor untouched
- a paged import advances through pages in order instead of re-reading page one
Asked to "add concurrency", an agent might persist the cursor inside an ensure block to keep progress moving, and the failed-root test catches that bug immediately. The importer also retries 429s and transient 5xx responses up to four times, honouring Retry-After or using bounded exponential backoff while writing a retry audit row so operations can see pushback. Because the shared production ceiling sits around 60 requests a minute, we capped the historical actions backfill at 40 requests a minute so staff using the same API kept headroom.
Snapshot first, then make the data useful
A root record isn't finished when a property row lands in PostgreSQL; the importer saves raw source snapshots first so we can debug projection bugs or upstream API changes months later. A refactor that merges fetch, transform, and persistence can drop snapshot writes while leaving row counts looking healthy, so the contract asserts both the external identifier on the local property and the presence of the snapshot.
Inspections pull detail, report data, metadata, contacts, attachments, and PDF generation endpoints, some of which are legitimately absent or temporarily down. Separate tests define which optional absences are tolerable and which required failures must abort the root, keeping cursor movement, snapshot retention, optionality, and retries readable when an agent edits them in one diff.
Freshness rules stop an old import overwriting a live change
The strictest rule governs time. Live webhooks arrive while the bulk importer walks historical pages, so a webhook can save a 10:05 update right before the importer processes a 09:58 snapshot. A blind upsert overwrites live data without throwing an error or triggering a retry.
The test builds that race in miniature: it seeds a record with the newer webhook timestamp, feeds the importer an older payload, and asserts the live value stays intact, then feeds a newer payload and asserts the update lands. Every forbidding rule needs its neighbouring permission case so an agent can't pass the suite by refusing all writes. For checking an existing system beyond what looks tidy in git, see the technical due diligence checklist.
Tests should tell the agent where its authority ends
My delegation loop stays short:
- Identify the behaviour that causes harm if guessed wrong.
- Write or tighten a test that fails on the broken behaviour and passes on the intended case.
- Ask the agent for the smallest change that makes that test pass, with an explicit boundary such as: "Modify the InventoryBase importer only. Preserve snapshot persistence. Do not change cursor representation. Add the smallest code needed for the failing cursor test."
- Read the diff as if the tests didn't exist, checking for extra abstractions, N+1 queries, or unrequested edits.
- Run the suite and keep the test for the next change.
I treat any test an agent writes as a proposal until I verify it fails before the fix and asserts an observable outcome at the system boundary (persisted cursor state, canonical upsert, or signed webhook gate) instead of mocking private helpers three layers down.
The small audio app shows the same rule at a different scale
A smaller iOS sound meter I built follows the same pattern with 34 unit-test methods across six files and seven UI tests. It reads microphone buffers, applies A-weighting, computes dBFS, estimates SPL, and renders SwiftUI state without recording or transmitting audio.
Its DSP tests lock down product decisions an agent mustn't alter in passing: invalid FFT sizing is rejected, a 1 kHz full-scale sine hits the expected level, 100 Hz reflects A-weighting attenuation normalised at 1 kHz, and silence floors at -120 dBFS instead of negative infinity so the UI never displays an unusable string. View-model tests clamp calibration to ±10 dB, reset session statistics cleanly, and swap in a fake NoiseMeter to stay fast and deterministic, while UI tests launch with UI_TESTING to skip live mic permissions and verify screens, paywalls, and accessibility identifiers without claiming physical acoustic accuracy on AVAudioEngine.
Check the historical data outside the test suite
Tests encode the rules we thought to write down; they can't pick 40 requests a minute over 35, notice an upstream field meaning shift, or prove every historical image downloaded. On the property migration, we paired the test suite with read-only production integrity checks, per-property manifests, live API comparisons, and a strict block on deleting source data until the actions backfill finished. Likewise, the audio app applies a documented 120 dB reference offset and lets users save a calibration against a reference meter, because no unit test can certify a phone microphone as lab hardware.
Before handing work to an agent, I ask which behaviour must never break and which assumption nobody has observed yet; the first becomes a test, and the second becomes a review or production check. When building AI-powered product features instead of using coding agents, my OpenAI API checklist applies those same boundaries to runtime contracts and failures.