TDD With an AI: Write the Test First, Then Prompt

· 7 min read ·
vibe-coding testing tdd ai

A man in a green sweater points at a glowing red signal lamp on a workbench while a small white robot in a detective hat sits ready with a screwdriver beside an unfinished gadget and a blueprint

Test-driven development with an AI means you describe the behavior you want as tests, watch them fail, and only then ask the AI to write the code that makes them pass. The failing run is the point: it proves the tests can catch something, and it gives the AI a target that is not “looks right to me”.

It works. It also has three ways to go quietly wrong, and each one ends in a green checkmark that means nothing. This post shows all three, run for real, with a copy-paste scratch repo.

What is red/green, in plain words?

Red is a test run that fails. Green is one that passes. The loop is: write the test, see red, write the code, see green.

Simon Willison, who writes about coding with agents, calls “use red/green TDD” a pleasingly succinct way to get better results, and says current models understand the phrase as shorthand for the longer instruction. His reasoning is the useful part: without the red step you risk a test that already passes, so it never proves your new code does anything. Anthropic’s Claude Code best practices describes the same workflow as one of its favorites: tests first, confirm they fail, commit the tests, then write code that passes them while being told not to modify the tests.

The guide also asks for independent checking that the code is not overfitting to the tests. That is trap 2 below.

A real example: how many days of trial are left?

You are adding a free trial. The rules, in plain English:

  • The trial is 14 days and the signup day counts as day 1.
  • On signup day you have 14 days left. On day 14 you have 1 left.
  • After that the answer is 0, never negative.

Set up a scratch folder and save these tests as trial.test.js:

Terminal window
npm init -y
npm pkg set type=module scripts.test="vitest run"
npm i -D vitest
import { it, expect } from 'vitest';
import { trialDaysLeft } from './trial.js';
it('on signup day you have all 14 days left', () => {
expect(trialDaysLeft('2026-12-01', '2026-12-01')).toBe(14);
});
it('on day 14 you have 1 day left', () => {
expect(trialDaysLeft('2026-12-01', '2026-12-14')).toBe(1);
});
it('the day after day 14 the trial is over and the answer is 0, never negative', () => {
expect(trialDaysLeft('2026-12-01', '2026-12-15')).toBe(0);
expect(trialDaysLeft('2026-12-01', '2027-02-01')).toBe(0);
});
it('works across a month and a year boundary', () => {
expect(trialDaysLeft('2026-12-25', '2027-01-02')).toBe(6);
});

These tests say what a user sees on a given date and nothing about how the days are counted inside. That is deliberate: a test of behavior survives a rewrite of the code and fails when a fix changes what the user sees. A test of internals does the opposite, as the behavior-tests post shows. Describe to the AI what the app does for a person.

Trap 1: the red that fails for the wrong reason

If the file trial.js does not exist yet, or you typo the import, npm test is red. A one-letter typo in the import path, in a scratch run, gave:

FAIL bad.test.js
Error: Cannot find module './trails.js' imported from /tmp/tdd/bad.test.js
Tests no tests

That is a broken file, not a failing test. It will be red forever and tell you nothing. A useful red shows a number that is wrong. Create trial.js with a stub that returns the wrong answer:

export function trialDaysLeft() { return 0; }
× on signup day you have all 14 days left
× on day 14 you have 1 day left
✓ the day after day 14 the trial is over and the answer is 0, never negative
× works across a month and a year boundary
AssertionError: expected +0 to be 14
Tests 3 failed | 1 passed (4)

With the four tests above, before the held-out one is added, read that closely. Three fail, for the right reason: the answer is 0 and should be 14. But one test is already green with no real code behind it. The stub happens to answer 0, which is what that test wants. A test that passes before the feature exists cannot prove the feature works. When you review a red run, look for the green ones and ask why.

Trap 2: the green the AI faked

Now suppose the AI “implements” it like this:

export function trialDaysLeft(signup, today) {
const known = {
'2026-12-01|2026-12-01': 14, '2026-12-01|2026-12-14': 1,
'2026-12-01|2026-12-15': 0, '2026-12-01|2027-02-01': 0,
'2026-12-25|2027-01-02': 6,
};
return known[signup + '|' + today];
}
Tests 4 passed (4)

All green, and it is a lookup table of your own examples. It is a cartoon version of overfitting. The failure it stands for is real: code shaped to pass the examples it was shown instead of the rule behind them.

The fix is one more test the AI has not seen. Keep it out of the prompt, add it after the AI says it is done, and run it:

it('held-out: a date pair the AI has not seen', () => {
expect(trialDaysLeft('2027-03-10', '2027-03-20')).toBe(4);
});
AssertionError: expected undefined to be 4
Tests 1 failed (1)

Now a first real implementation:

const DAY = 24 * 60 * 60 * 1000;
export function trialDaysLeft(signup, today) {
const used = Math.round((Date.parse(today) - Date.parse(signup)) / DAY);
return Math.max(0, 14 - used);
}

All five tests pass, held-out one included. It is still wrong, and the tests cannot see it, because every test uses a date-only string. A real app calls it with a timestamp from the database or from new Date().toISOString(). Add two behaviors a user would notice. The first: on the evening of day 14, the user still has 1 day left. The second: the same instant is already the next day for someone in India, so “today” needs an owner.

it('on the evening of day 14 a full timestamp still has 1 day left', () => {
expect(trialDaysLeft('2026-12-01', '2026-12-14T20:30:00Z')).toBe(1);
});
it('a user in India is already on day 15 at that instant, so 0 days left', () => {
const signup = '2026-12-01T03:30:00Z'; // 9:00 on 1 December in India
const now = '2026-12-14T20:30:00Z'; // 2:00 on 15 December in India
expect(trialDaysLeft(signup, now, 'Asia/Kolkata')).toBe(0);
expect(trialDaysLeft(signup, now, 'UTC')).toBe(1);
});

Against the first implementation, in a scratch run (vitest 5.1.2, Node 22), both fail with expected +0 to be 1. The cause of the first: 20:30 on day 14 is 13.85 days after midnight, and Math.round turns that into 14 days used. The second needs a decision your code cannot make alone: whose midnight ends the trial, the user’s or the app’s? AI-written code usually picks UTC without saying so. Put the timezone in your rules. A date-only string is read as UTC and a timestamp without a timezone as local time, per MDN, so mixing them is another way to land a day off.

The fix counts calendar days in one named timezone:

const DAY = 24 * 60 * 60 * 1000;
function calendarDay(value, timeZone) {
if (/^\d{4}-\d{2}-\d{2}$/.test(value)) return value; // already a plain date
return new Intl.DateTimeFormat('en-CA', { timeZone }).format(new Date(value));
}
export function trialDaysLeft(signup, now, timeZone = 'UTC') {
const used =
(Date.parse(calendarDay(now, timeZone)) - Date.parse(calendarDay(signup, timeZone))) / DAY;
return Math.max(0, 14 - used);
}

All seven tests pass.

Trap 3: the AI edits the test

When code will not pass a test, an AI has two ways out. It can fix the code, or it can change the test. Both end green. So:

  1. Commit the tests before you ask for code: git add -A && git commit -m "tests: trial days left".
  2. Say in the prompt: do not edit the tests. For a hard guard, a pre-commit or CI check that fails when a test file changes in a code-fix commit does the same job without trusting the AI (a suggestion, not run for this post).
  3. After the AI is done, run git diff --stat and look for the test file. It should not be in the list. If it is, read what changed.

A prompt to paste

Use red/green TDD. Write the tests first, from this description only: [paste your plain-English rules with example numbers]. Do not write the implementation yet. Run the tests once with npm test and show me the output. Every failing test must fail on a wrong answer, not on a missing file or an import error, and tell me about any test that passes before the code exists. Stop and wait. After I commit the tests, write the simplest code that makes them pass. Do not edit the tests. Do not special-case the example values. Use dates with times and a timezone in at least one test. Run the tests again and show me the output.

What about changing code that already exists?

Red/green fits new behavior best. For changing existing code, the evidence is more mixed. A March 2026 paper (Alonso, two small local models on SWE-bench Verified) found that telling an agent to do TDD with no other help raised how often it broke previously passing tests, to 9.94%. Giving the agent a list of the existing tests its change could affect, worked out by a graph-based impact-analysis tool, cut breakage by 70% (6.08% to 1.82%). Caveat: two small models, Python projects, one study. So do not stop at “do TDD”: run the whole existing suite before and after the change, and tell the AI which tests cover the area it touches. The bug-loop post has the routine.

The one check an engineer does by hand

Look at the red run before you let the AI write any code. Count the failures, read the error on each, and find any test that is already green. If you cannot say why each red test is red, the green that follows will not mean much.

New to tests? Start with tests for people who do not write code, which covers how to check that the tests you get are real. The launch checklist shows where tests sit in the larger picture.

The Get AI Native ebook goes deeper on this. It is free, and the expected launch is around Christmas. Join the waitlist on the homepage.

Comments