Test-driven development with Claude Code: a practical loop

How to do test-driven development with Claude Code: write the failing test first, keep Claude from rewriting it, and enforce green with a Stop hook.

· 6 min read

Test-driven development fits Claude Code well because it gives the agent what it lacks most: a pass or fail result it can read. Write the failing test (or have Claude write it and approve it), then let Claude change the code until the test passes. This page shows the loop, the prompts, and the two guardrails that stop the usual failure, which is Claude "fixing" the test instead of the code.

#Why does TDD suit Claude Code?

Claude Code's own best-practices page puts it plainly: Claude stops when the work looks done, and if it has nothing to run that says whether the work really is done, "looks done" is all it has. In practice you become the test suite.

A test turns that around. Claude makes a change, runs the check, reads the output, and fixes what broke before running it again, without you in the loop. The check can be a test file, a build's exit code, a linter, or a script that diffs output against a fixture. A failing test written before the code is the sharpest version, because it also tells Claude exactly what "done" means.

#How to run the red-green-refactor loop

Keep each step as its own prompt, and keep each cycle small: one behavior, one test.

1. Red. Ask for the test only, and tell Claude not to touch the implementation:

Write a failing test for rate limiting in src/api/limiter.test.ts: a 6th request
within one minute from the same IP returns 429. Do not change src/api/limiter.ts.
Run the test and show me the failure output.

Read the failure. A test that fails for the wrong reason (an import error, a typo) proves nothing. You want it to fail on the assertion.

2. Green. Approve the test, then:

Make that test pass with the smallest change. Run the whole limiter test file after
each change and keep going until it passes. Don't edit the test.

3. Refactor. Once green, ask for cleanup with the suite as a safety net:

Refactor limiter.ts for readability. Run the tests; they must stay green.

For a bug, the same shape works: the docs' own example asks Claude to "write a failing test that reproduces it, then fix it". The reproduction test stays in the repo as a regression test.

#What should the CLAUDE.md say about tests?

Claude needs the exact commands, including how to run a single file. The best-practices page calls the command that runs your check the single most useful line in a CLAUDE.md:

Tests:
- Run one test file: pnpm vitest run path/to/file.test.ts
- Run everything: pnpm test
- Typecheck: pnpm tsc --noEmit
- Write the failing test first, show the failure, then implement.
- Never edit an existing test to make it pass; ask me first.

The last two lines are guidelines, and Claude is allowed to weigh a guideline. If a rule must hold every time, enforce it, as below. More on writing this file in How to write a CLAUDE.md that Claude Code actually follows.

#How do you stop Claude from editing the test to pass?

This is the real risk of TDD with an agent. Faced with a red test, the cheapest fix is sometimes to loosen the assertion. Three layers help, from soft to hard.

Say it in the prompt. "Don't edit the test" in the green step catches most cases, and a diff review catches the rest. Always look at whether the test file changed.

Ask for evidence. Request the command Claude ran and its output, not just "all tests pass". Reading the output takes seconds.

Lock the tests with a hook. A PreToolUse hook can block Edit and Write on test files while a marker file exists. Claude Code's hooks guide shows this mechanism for protected files: the script reads the tool input as JSON on stdin and exits with code 2 to block the edit, and what it prints to stderr goes back to Claude as the reason.

#!/bin/bash
# .claude/hooks/lock-tests.sh
INPUT=$(cat)
FILE_PATH=$(echo "$INPUT" | jq -r '.tool_input.file_path // empty')

if [ -f "$CLAUDE_PROJECT_DIR/.claude/tests-locked" ] && [[ "$FILE_PATH" == *.test.* ]]; then
  echo "Tests are locked. Change the code, or ask the user to unlock." >&2
  exit 2
fi
exit 0
{
  "hooks": {
    "PreToolUse": [
      {
        "matcher": "Edit|Write",
        "hooks": [
          { "type": "command", "command": "\"$CLAUDE_PROJECT_DIR\"/.claude/hooks/lock-tests.sh" }
        ]
      }
    ]
  }
}

Run chmod +x on the script, and create the marker (touch .claude/tests-locked) once you approve the red test. Remove it when you want new tests. Note that Claude can still change files through shell commands, so treat this as a guardrail, not a vault. See Claude Code hooks for the full model.

#How do you make Claude keep going until the suite is green?

Three options, in rising order of strictness:

  • In the prompt: "run the auth tests after, and keep going until they pass". No setup.
  • A goal: /goal all tests in tests/auth pass and lint is clean sets a condition that a separate model checks after every turn. It helps most on long unattended runs, where Claude sometimes ends a turn with a progress summary while items are still open.
  • A Stop hook: it runs your script whenever Claude tries to end its turn, and sends Claude back to work if the script exits with code 2.
{
  "hooks": {
    "Stop": [
      {
        "hooks": [
          { "type": "command", "command": "pnpm test 1>&2 || exit 2" }
        ]
      }
    ]
  }
}

The test output goes to stderr, so Claude reads the failures as the reason it cannot finish. The hook is enforced by Claude Code itself, not by the model. There is a cap: if it blocks eight stops in a row with no tool call between them, Claude Code overrides the next block and ends the turn. Keep the command fast, or run only the affected tests, since it fires every time Claude tries to stop.

#Should you plan the tests first?

For anything bigger than one function, yes. Switch to plan mode (claude --permission-mode plan, or Shift+Tab until the status bar shows plan mode) and have Claude propose the test list: the cases, the edge cases, the files. Edit the list, write it to a SPEC.md, then start a fresh session to build from it, so the build begins with a clean context and a written definition of done. See Plan mode in Claude Code.

To check the result against the plan, the docs suggest a reviewer subagent with a narrow brief:

use a subagent to review the diff against SPEC.md, check every requirement is
implemented and the listed edge cases have tests, report gaps that affect correctness and skip style

Keep "skip style". A reviewer asked to find problems will always find something, and fixing every finding is how you end up with abstraction layers and tests for cases that cannot happen. More in Using Claude Code to review code.

#What if a cycle goes wrong?

Small cycles make this cheap. Press Esc as soon as Claude drifts. /rewind, or Esc twice on an empty prompt, rolls code, conversation, or both back to an earlier prompt. Checkpoints cover files Claude edited with its own file tools, not files a Bash command touched, and they work alongside git rather than replacing it. After two failed corrections, /clear and write a better prompt rather than a third correction. Committing after each green step gives you a hard floor; see How to undo what Claude Code changed.

#Checklist for each cycle

  • One behavior per cycle, with the test command in CLAUDE.md.
  • The red test fails on the assertion, not on an import.
  • "Don't edit the test" in the green prompt, or the lock hook.
  • Evidence in the answer: the command and its output.
  • Tests green, then a commit, then refactor.

#In Relais

Relais is a desktop app on top of Claude Code, so everything above works as is. Three parts help this loop: the Run tab saves your test command per folder (for example pnpm test) and its "Send logs to Claude" drops the tail of a failing run into the composer; the undo arrow on any of your messages puts back every file Claude changed after it, even outside git; and the Changes tab shows the diff so you can see whether a test file moved. Details on the features page.

Claude Code,
better organized.

$14.99 a month, everything included. Mac and Linux, on your Claude Pro or Max plan. Cancel any time.