Skip to content
AI Skills Central

Type to search Agent Skills, workflows, tutorials, tools and the glossary.

Workflow recipe

Test-driven development with a coding agent

Agree the seams, write one failing test, lock the tests with a hook while the agent makes it pass, then prove the test can fail.

By Checked Intermediate1 h 30 min7 steps
Bookmark

Bookmarks are kept in your free account, so you can find this page again on any device.

Sign in to bookmark
On this page

To do TDD with an AI coding agent, agree the public seams you will test before any code, then work one slice at a time: the agent writes one failing test, you check it fails for the right reason, you switch the repository to a “green” phase in which a hook makes test files read-only, and the agent writes the least code that passes. A second hook refuses to let the agent finish while the tests fail. You prove each test by breaking the code once, commit, and repeat.

Agents are fast at writing tests and code together, which is the problem. Asked to “add tests and make them pass”, an agent can write the implementation first and tests that mirror it, or quietly loosen an assertion when the code does not do what the test expects. Both leave you with green tests that would never catch a bug. Test-driven development fixes this with an order of work: the test exists, and fails, before the code. With an agent, you also have to enforce that order, because instructions alone drift over a long session. This recipe uses Claude Code hooks to enforce it and two published TDD skills to shape the tests.

TerminalAbout 5 min

1. Install one TDD skill

Two skills in our directory teach an agent the loop, and they fix different failures. Pick the one for the problem you see:

  • tdd (Matt Pocock) is short and about test design: agree the seams first, test only through public interfaces, and avoid tautological assertions that recompute the expected value the way the code does.
  • test-driven-development (Superpowers) is stricter about process: watch every test fail, write the least code to pass, and do not skip red.

If your agent skips the failing step, use the second. If it follows red-green but writes brittle or meaningless tests, use the first. Install commands for each agent are on the listing pages, pinned to the commit we reviewed. They work together if you want both.

Claude CodeAbout 15 min

2. Agree the seams and a test list before any code

A seam is the public boundary you test at: a function’s signature, an HTTP route, a component’s props. Tests at seams survive refactoring; tests against internals break on every change. Ask the agent to propose them, and to write nothing yet.

Seams and test list · Claude Code or Codex
We are going to build [FEATURE] test-first, one test at a time. Before writing any code or tests: 1. Read [FILES OR DIRECTORY] and propose the public seams to test at. For each seam, one line on what a test there catches and what it misses. 2. Write a test list: the behaviours to cover, as short sentences with a concrete example input and expected output each, ordered from simplest to hardest. Rules: - Do not create or edit any file yet. - Expected outputs must come from the spec or worked examples, never from running existing code. - Mark any behaviour where the expected result is a decision I have to make with "DECIDE".

Read the list. Strike behaviours you do not need, answer every “DECIDE”, and add the edge case you know about from production. Save the agreed list as TESTLIST.md; each slice in the next steps takes the top unchecked item.

Editor and terminalAbout 20 min

3. Add the hooks that enforce the phase

Two hooks hold the loop in place. The phase lives in a one-word file, .tdd-phase, that only you change. In the red phase the agent may edit only test files. In the green phase test files are read-only, and the agent cannot end its turn while the tests fail.

Create .claude/hooks/tdd-guard.sh for the Edit and Write tools, which send the target path as tool_input.file_path:

#!/usr/bin/env bash
# PreToolUse hook for Edit and Write: enforce the TDD phase in .tdd-phase ("red" or "green").
# Red: only test files may change. Green: test files are read-only. Only you change the phase.
set -euo pipefail

FILE=$(jq -r '.tool_input.file_path // ""')
PHASE=$(cat "$CLAUDE_PROJECT_DIR/.tdd-phase" 2>/dev/null || echo "red")

deny() {
  jq -n --arg r "$1" \
    '{hookSpecificOutput: {hookEventName: "PreToolUse", permissionDecision: "deny", permissionDecisionReason: $r}}'
  exit 0
}

is_test() {
  case "$1" in
    */tests/*|*/test/*|*/__tests__/*|*.test.*|*.spec.*|*_test.*|*/test_*.py) return 0 ;;
    *) return 1 ;;
  esac
}

[ "$(basename "$FILE")" = ".tdd-phase" ] && deny "Only the person running the session changes the TDD phase."

if [ "$PHASE" = "green" ] && is_test "$FILE"; then
  deny "Green phase: $FILE is a test file and is read-only. Change the code under test, or stop and explain why the test is wrong."
fi

if [ "$PHASE" = "red" ] && ! is_test "$FILE"; then
  deny "Red phase: write the failing test first. $FILE is not a test file."
fi

exit 0  # no decision: normal permissions apply

Create .claude/hooks/tests-must-pass.sh for the Stop event. Exit code 2 from a Stop hook keeps Claude working and passes the message on stderr to it as the reason. The stop_hook_active check lets it stop the second time, so a test it cannot fix does not loop forever:

#!/usr/bin/env bash
# Stop hook: in the green phase, Claude cannot finish its turn while the tests fail.
set -uo pipefail

INPUT=$(cat)
PHASE=$(cat "$CLAUDE_PROJECT_DIR/.tdd-phase" 2>/dev/null || echo "red")
[ "$PHASE" = "green" ] || exit 0
# Already continuing because of this hook once: let it stop, so it cannot loop.
[ "$(echo "$INPUT" | jq -r '.stop_hook_active')" = "true" ] && exit 0

cd "$CLAUDE_PROJECT_DIR"
if ! OUTPUT=$(npm test --silent 2>&1); then
  echo "Tests fail in the green phase. Fix the code, not the tests:" >&2
  echo "$OUTPUT" | tail -n 30 >&2
  exit 2
fi
exit 0

Make both executable with chmod +x .claude/hooks/*.sh, change npm test --silent to your test command, and adjust the test-file patterns in is_test to your layout. Register them in .claude/settings.json:

{
  "hooks": {
    "PreToolUse": [
      {
        "matcher": "Edit|Write",
        "hooks": [
          { "type": "command", "command": "${CLAUDE_PROJECT_DIR}/.claude/hooks/tdd-guard.sh", "args": [] }
        ]
      }
    ],
    "Stop": [
      {
        "hooks": [
          { "type": "command", "command": "${CLAUDE_PROJECT_DIR}/.claude/hooks/tests-must-pass.sh", "args": [] }
        ]
      }
    ]
  }
}

Test the guard before you trust it, by sending it the same JSON Claude Code would:

export CLAUDE_PROJECT_DIR=$PWD
for phase in red green; do
  echo "$phase" > .tdd-phase
  for f in "$PWD/tests/slug.test.js" "$PWD/src/slug.js" "$PWD/.tdd-phase"; do
    out=$(jq -n --arg f "$f" '{tool_name: "Edit", tool_input: {file_path: $f}}' | .claude/hooks/tdd-guard.sh)
    decision=$(printf '%s' "$out" | jq -r '.hookSpecificOutput.permissionDecision')
    echo "$phase  $(basename "$f")  -> ${decision:-none}"
  done
done

You should see exactly this:

red  slug.test.js  -> none
red  slug.js  -> deny
red  .tdd-phase  -> deny
green  slug.test.js  -> deny
green  slug.js  -> none
green  .tdd-phase  -> deny

“none” means the hook made no decision and normal permissions apply. Commit the hooks and settings so every session gets them. Add .tdd-phase to .gitignore; it is your local state, not the team’s.

Claude CodeAbout 10 min

4. Red: one failing test, and check why it fails

Set the phase and ask for one test only:

echo red > .tdd-phase
Write one failing test · Claude Code
Take the first unchecked item in TESTLIST.md and write one test for it, at the agreed seam. Rules: - One test only. Do not touch any non-test file; the hooks will refuse it. - The expected value must be a literal from the test list, not computed the way the code would compute it. - Run [TEST COMMAND] and show me the failure output. Then stop and wait.

Read the failure before you go on. It must fail on the assertion, with the expected and actual values you would predict. A failure for any other reason (a missing import, a syntax error, a test runner that cannot find the file) proves nothing about the behaviour. In our run, a test script of node --test tests/ failed on Node.js 22 with Cannot find module '.../tests' before running a single assertion. The agent spotted it, ran the file directly to show the real failure, and left package.json alone because the guard only allowed test files. Changing the script to plain node --test, which finds *.test.js files itself, produced the failure you want to see:

not ok 1 - turns spaces into single hyphens
  expected: 'hello-big-world'
  actual: 'hello   big world'

If the new test passes straight away, either the behaviour already exists (tick it off the list) or the test is not testing what it says. Do not go to green with a test you have not seen fail.

Claude CodeAbout 15 min

5. Green: the least code that passes, with the tests locked

Commit the failing test on its own, so the next diff shows code only. Then switch the phase yourself and ask for the implementation:

git add tests/ && git commit -m "test: spaces become single hyphens (red)"
echo green > .tdd-phase
Make it pass · Claude Code
Make the failing test pass with the smallest change to the code under test. Rules: - Test files are read-only in this phase. If you believe the test is wrong, stop and explain why instead of working around it. - Do not add behaviour that no test asks for. No speculative options, no refactoring yet. - Run [TEST COMMAND] and show me the full result when it passes.

If the agent tries to edit a test file, the guard denies the call and tells it why; it should then change the code or stop and explain. If it tries to finish with failing tests, the Stop hook sends it back with the test output. If it still cannot pass after that second attempt, it stops: read its explanation, because a test that is hard to pass with a small change is often a test at the wrong seam.

TerminalAbout 10 min

6. Prove the slice: the test can fail, and the tests did not move

Two checks, both quick, and both the reason this recipe exists.

First, confirm that no test file changed during the green phase. Because you committed the red test in step 5, the diff since that commit should contain code only:

git diff --stat HEAD -- tests/

An empty result is what you want. The hook covers Edit and Write, but an agent with shell access could still change a file through a shell command, so this diff is the real check. If you want a hard stop there too, add a deny rule for shell writes into your test folder, as in the guardrail hooks recipe.

Second, break the code once. Revert the one line that matters, or return a wrong constant, and run the tests. The new test must fail. If it still passes, it is not testing the change, whatever its name says. Restore the line.

Terminal and Claude CodeAbout 15 min

7. Commit the slice, repeat, and refactor with the tests frozen

Commit the code with a message naming the behaviour (squash it into the red commit if your team prefers one commit per behaviour), tick the item in TESTLIST.md, set the phase back to red and take the next item. Keep slices small: one behaviour, one test, a few lines of code. Long slices are where agents start writing tests to fit code they already wrote.

After a few slices, refactor in green with every test locked. Ask the agent to improve names and structure without changing behaviour; the guard keeps the tests fixed, and the Stop hook keeps them passing. Review the refactor as a separate commit, so a reviewer can see the behaviour did not change.

Check it worked

Verification checklist

0 of 6 done

When it goes wrong

If the red test fails with a module-not-found or “no tests found” error, the test runner configuration is wrong, not the code. Fix the test command first and re-run until the failure is the assertion you expect. We hit this with a directory argument to node --test; Jest and pytest have their own versions of it, such as a test file outside the configured pattern.

If the guard lets a test file edit through in green, the file does not match the is_test patterns. Check the path the hook received by logging tool_input.file_path to a file, then add the pattern. Hooks fail open, so a script with a syntax error or a missing jq also lets everything through: re-run the guard test after every change to the script.

If the agent keeps stopping in green with an explanation that the test is wrong, read it. Sometimes it is right: the expected value in the test list was a guess, or the test reaches through an internal. Switch to red yourself, fix the test with the agent, and record the decision in TESTLIST.md.

If the Stop hook makes every turn slow, your test command is too slow for the loop. Point the hook at the fast unit tests for the module you are working on, and run the full suite in CI.

Variations

In Codex, put the hooks in .codex/hooks.json in a trusted project and review them with /hooks, because Codex skips new or changed hooks until you trust them. Codex accepts permissionDecision: "deny" from a PreToolUse hook and has a Stop event that continues the turn on exit code 2, so the Stop script works as it is. The guard needs one change: Codex edits files through apply_patch, and although the matcher may say Edit|Write, the hook receives the patch text in tool_input.command rather than a file_path. Read the paths from the patch’s *** Update File:, *** Add File: and *** Delete File: lines and run each through is_test.

For code that has no tests yet, unit tests for legacy code pins down what the code does today before you change it; then switch to this loop for new behaviour. To find tests that pass but catch nothing across a whole suite, run mutation testing with the mutation-testing skill; it automates step 6’s “break it on purpose”.

For bigger features, write the spec first with the spec-driven feature build recipe and turn its acceptance criteria into the test list.

The Claude Code hooks tutorial explains every hook event used here. How to review AI-written code covers what else to look for in the diff, and the AI for test engineers path puts this recipe in context with test generation and flaky-test repair.

Outcome and tools

Outcome
A feature built in small red-green slices, each with a test you saw fail for the right reason, and hooks in the repository that stop the agent editing tests to make them pass.
For
Developers, QA engineers
Variants for
Claude Code, Codex
  • Set up guardrail hooks for your coding agent

    Block dangerous commands in Claude Code with PreToolUse hooks and deny rules, so the agent cannot force-push, wipe files or edit secrets. Test them first.

    WorkflowIntermediate1 h6 steps

  • Write unit tests for legacy code with a coding agent

    An agent writes characterisation tests, you check for weak assertions and prove them with mutation testing.

    WorkflowBeginner1 h6 steps

  • Claude Code hooks: run checks around every tool call

    Write Claude Code PreToolUse and PostToolUse hooks that block destructive shell commands, format every file Claude edits and log each command for later audit.

    TutorialIntermediate40 min

  • Reviewing AI-written code: what to look for

    The ways agent-written diffs fail, a practical review checklist, and how to set up the work so review stays manageable.

    Article

  • AI for test engineers

    An AI course for testers: apply generative AI to everyday test automation, from AI-assisted test design to generating, healing and reviewing Playwright tests.

    Learning pathBeginner9 h10 steps

Back to top