Best practice L2 · Context engineering informational

Ask for the Test That Would Have Caught the Bug

What it is

A rule for bug fixes: before Claude changes any code, have it write the single test that fails today because of the bug and will pass once the bug is gone. The test, not the patch, is the deliverable you review first.

test firstBug foundWrite failing testFix codeTest stays green
A fix without a guarding test is a fix that will be undone.

Why it works

Most AI bug fixes are unguarded — they change behaviour with nothing to stop the same bug returning in a refactor six weeks later. A failing test forces Claude to name the exact condition that is broken, gives you a red/green signal that the fix is real, and leaves behind a permanent tripwire. It also catches the common failure where the model 'fixes' a symptom that was never actually the cause: if the test it writes doesn't fail before the change, the theory is wrong.

When to use it

Every non-trivial bug in code that has, or could have, a test suite — logic errors, boundary conditions, wrong output, state that corrupts under a specific sequence.

When not to use it

Throwaway scripts, spikes, or code with no test harness at all where standing up one costs more than the fix is worth. Don't bolt a test framework onto a ten-line prototype.

Prompt

Bug: <describe the wrong behaviour, expected vs actual>.
Relevant code: <paste the slice, not the repo>.

Step 1: Write one failing test that reproduces this bug. Show me the test and confirm it fails against the current code and why.
Step 2: Only after I approve the test, make the smallest change that turns it green without breaking the surrounding tests.

Example

A cart total is wrong when a discount code is applied to a single item. Claude writes expect(total(cartWith(oneItem, code10off))).toBe(9), confirms it currently returns 10, then changes where the discount is folded in — and you trust the fix because the number moved for the right reason.

Advanced version

Ask Claude to write the test at the lowest layer that still reproduces the bug. A unit test on the pricing function is a better tripwire than an end-to-end test that also breaks when the checkout button moves.

Common mistakes

  • Letting Claude write the fix and the test in one turn — the test is then shaped to pass the fix, not to describe the bug.
  • Accepting a test that passes before the change is made; that proves nothing.
  • Testing the symptom (the visible number) instead of the mechanism, so the bug reappears in a new shape.

Related