Demo, all content is generated
Question

Getting Claude Code to write the failing test first, it always writes the code too

Open · 485 views · asked by sophie_l · edited

I want to try test-first: write a test, see it fail, then write the code. But whatever I say, Claude Code writes the test AND the implementation in one go, then runs the tests and they pass. So I never see a red test and I'm not sure the test would ever have caught anything.

Is there a way to make it stop after the test?

What I’ve tried

Said 'only write the test' (it still wrote the code 'to make it pass'), put 'test first' in CLAUDE.md.

Comment
Are you in plan mode or normal mode when you ask? katja_s · edited

3 answers

katja_s · edited

Make "stop" a concrete, checkable step instead of a wish:

Write a failing test for X in tests/x.test.ts. Run it. Show me the failure output. Then stop and wait for me. Do not edit anything outside tests/.

The "show me the failure" part matters. If it can't produce red output, the test isn't testing anything new, and you learn that before any code exists.

Then a second message: "Now make that test pass with the smallest change. Don't modify the test."

Two messages, not one. Asking for both in one prompt is where it collapses them.

Comment
Two messages works. It actually showed me a red test and waited. sophie_l · edited
Sometimes it still sneaks in a 'small helper' in src/ with the test though. sophie_l · edited
marco_py · edited

Structural fix for the sneaking: a hook that blocks edits outside tests/ during the red phase, or simply check git status after step one and throw away anything in src/.

Also look at what it asserts. A test written by the same model that will write the code tends to test the shape it already has in mind. I write the test names myself ("rejects a booking in the past", "allows two bookings back to back") and let it fill in the bodies. That's where the value is.

Comment
Agree on writing the names yourself. That's the spec, the rest is typing. katja_s · edited
thandeka · edited

Plan mode helps too: ask for the test in plan mode, approve, it writes only what the plan said. Not bulletproof, but less sneaking.

Comment