Skip to content
Mindela

By · November 20, 2026 · 7 min read

Test-Driven Development With Claude Code: The Spec, Failing Test, Implement Loop

Claude CodeTesting

Test-driven development with Claude Code is a loop: write the acceptance criteria, have Claude write tests that fail, review and commit those tests, then have Claude implement the smallest change that makes them pass. The tests are the one form of verification an agent cannot talk its way past.

The reason to do this is trust. An agent that says "done" without proof is the most common way AI-assisted work goes wrong, and a failing-then-passing test is proof you can rerun.

What is test-driven development with Claude Code?

Test-driven development (TDD) is a practice where you write a failing test before the code that satisfies it. The classic cycle has three phases: red (a test fails for the right reason), green (the smallest change makes it pass) and refactor (improve the structure while tests stay green).

With Claude Code the phases are the same, but the roles change. The developer defines behavior and reviews the tests. The agent writes test code, runs the suite, reads failures and writes the implementation. Because Claude Code can run commands and read their output, the red-green feedback loop happens inside one session.

Why does TDD suit AI coding agents?

Agents are fluent, fast and sometimes wrong in ways that read as correct. Anthropic's Claude Code best practices trace one common failure to exactly this: Claude says it is done when it is not, usually because it had no way to check its own work. The fix is to give it a check to run, and a test suite is the strongest check most teams already own.

The trust gap is measurable at industry scale. In the 2025 Stack Overflow Developer Survey, 84% of respondents said they use or plan to use AI tools, yet more developers actively distrust the accuracy of AI output (46%) than trust it (33%), and only 3% reported highly trusting it. Adoption has outrun trust, and tests are how teams close that gap without slowing down.

What is the spec, failing test, implement loop?

Follow these steps for any feature with real logic:

  1. Write acceptance criteria. Plain-language, observable results. If you use spec-driven development with Claude Code and Spec Kit, these come straight from the spec.
  2. Ask for tests only. Tell Claude to write tests for the criteria and not to touch implementation code.
  3. Confirm red. Have Claude run the tests and show that they fail, and that they fail for the intended reason, not because of a typo or a missing import.
  4. Review and commit the tests. A human reads them against the criteria. The commit is the checkpoint: from here, tests are the fixed target.
  5. Implement the smallest change. Instruct Claude to make the tests pass without editing them, running the suite after each change.
  6. Confirm green. Run the full suite, not only the new tests, and read the output.
  7. Refactor while green. Improve names and structure with the suite as the safety net.
  8. Add edge-case tests. Ask what is missing: boundaries, failure paths, concurrency, bad input. Repeat from step 3 for each.

The ordering matters more than the tooling. Thoughtbot describes the same human-in-the-loop shape in a Rails example: Claude writes failing tests, the developer reviews and commits them, then Claude makes the smallest change that passes.

Which prompts work at each phase?

Prompts should be specific about the phase and the constraint. The best practices guide gives the pattern for a bug: describe the symptom, ask for a failing test that reproduces it, then ask for the fix.

PhasePrompt patternGuardrail to state
Red"Write tests for these acceptance criteria. Do not write implementation code. Run them and show me the failures."Failures must come from missing behavior, not syntax errors
Review"List which acceptance criterion each test covers and which criteria have no test."Gaps are fixed before any code exists
Green"Make the failing tests pass with the smallest change. Do not edit the tests. Run the full suite after each change."No test edits, no skipped tests
Refactor"Simplify this without changing behavior. Run the suite before and after."Suite must be green at both ends
Edge cases"What behavior is untested? Propose tests for boundaries and failure paths, then wait."Human approves new tests before implementation

For a bug fix, the phase list collapses: reproduce the bug with a failing test, make it pass, confirm nothing else broke.

How do you stop Claude Code from gaming the tests?

An agent optimizing for a green result can take shortcuts. Watch for these:

  • Editing the test to match the buggy behavior.
  • Hardcoding the expected value instead of computing it.
  • Mocking the thing under test, so the test checks the mock.
  • Deleting or skipping a failing test.
  • Writing tests that mirror the implementation, so they pass for any behavior.
  • Claiming success without running the suite.

Prompts reduce these, but they do not guarantee anything. Anthropic's best practices make the distinction explicit: instructions in a prompt, CLAUDE.md or a skill are non-deterministic, because the model decides whether to follow them, while hooks, deny rules and managed settings are applied by Claude Code every time. If you keep adding emphasis to a line and the agent still misses it, that line belongs in a hook.

Apply that to TDD:

  • Protect committed tests. Use a permission deny rule or a hook so edits to the test directory are blocked during the green phase.
  • Require evidence. Have the agent paste the actual test output, and let CI be the final gate.
  • Review test diffs separately. Any change to a committed test in a pull request is a deliberate decision, not a side effect.
  • Check test strength. Mutation testing tools break your code in small ways and see whether the tests notice. Tests that survive the mutations are decoration.

How do you encode TDD in CLAUDE.md, hooks and subagents?

Put the habits in three layers:

Project instructions. A short section in CLAUDE.md stating the test command, the rule that a failing test comes first for features and bug fixes, and the rule that committed tests are not edited to pass. Keep it to a few lines. The best practices guide advises writing down only what Claude cannot find by reading the repository.

## Testing
- Run tests with: npm test (fast subset: npm test -- --changed)
- Features and bug fixes start with a failing test. Show the failure first.
- Never edit, skip or delete a committed test to make it pass.
  If a test looks wrong, stop and ask.
- Before saying a task is done, run the full suite and paste the result.

Deterministic enforcement. A deny rule on the protected test paths. A Stop hook that runs the test command and sends Claude back to work when the suite is red, instead of letting it end its turn. Both are applied by the harness regardless of what the model decides, though a Stop hook gives way after a set number of consecutive blocks, so keep CI as the final gate.

Role separation. Subagents can split the work so the agent that writes tests is not the one that implements them. This reduces the temptation to bend a test toward the code, and it keeps each context focused. Several community skills use this pattern, but treat any third-party skill as code to review before you install it.

Where does TDD with Claude Code break down?

Legacy code with no tests. Start with characterization tests that capture what the system does today, review them, and only then change behavior.

User interface work. Visual correctness is hard to assert. Test the logic underneath, and use screenshots or browser checks for the rest.

Flaky tests. An agent will chase a flaky failure as if it were real. Fix or quarantine flakiness before asking an agent to iterate against the suite.

Slow suites. A ten-minute suite makes the loop painful. Give the agent a fast subset for iteration and run the full suite at the end.

External systems. Use contract tests or controlled fakes, and be explicit about which behavior is faked.

Wrong tests, right code. The loop faithfully delivers whatever the tests describe. This is why step 4 is a human review, not a formality.

How do you know it is working?

Do not count generated tests. Compare outcomes on comparable work before and after you adopt the loop:

  • escaped defects and rollbacks;
  • review rounds and reviewer time per pull request;
  • how often committed tests were modified during implementation;
  • meaningful coverage of the behavior you touched;
  • time from task start to an accepted change.

Our guide to rolling out Claude Code and Codex across an engineering team covers how to set the baseline and run a four-week pilot around these measures.

Why this is the backbone of our programs

The spec-then-test loop is the working method we teach engineering teams hands-on. The one-week Morgan Stanley Claude Code program, delivered to 600 participants from C-suite leaders to senior engineers, was built on spec-driven and test-driven development, because a method that checks agent output against written intent is far easier to defend in a regulated firm than one that trusts the output on sight.

If you want your developers practicing this on their own repositories, see our Claude Code training program or start a conversation about your team's needs.

Frequently asked

Does test-driven development work with Claude Code?

Yes, and it suits agents well. A failing test gives Claude Code an executable definition of done, so it can run the suite, read the failure and keep iterating until the behavior is correct. The human stays responsible for reviewing that the tests describe the right behavior.

Should Claude Code write the tests or should developers?

Claude Code can draft tests quickly, but a human must review them before implementation starts, because a wrong test makes a wrong implementation look correct. For critical business logic, have the developer write or heavily edit the tests and let the agent write the code.

How do I stop Claude Code from editing tests to make them pass?

Commit the tests before implementation, tell the agent not to modify them, and enforce it with a permission deny rule or a hook rather than only a prompt. Then review any change to test files in the pull request as a separate, suspicious event.

What is the red-green-refactor cycle?

Red means write a test that fails for the right reason. Green means write the smallest change that makes it pass. Refactor means improve the structure while the tests stay green. Claude Code can run each phase, but the loop only works if the red step is confirmed before any code is written.

Does TDD make Claude Code slower?

It adds a review step up front, which costs minutes. It usually saves time on features with real logic, because failures surface as test output within the session instead of as review comments days later. For trivial changes the overhead is not worth it.

Working through this decision yourself?

We’re happy to pressure-test your thinking. Engineering opinions, no sales sequence.

Talk to an engineer