Track lessons
WorkflowsTestingClaude CodeIntermediate4 min

Agentic TDD: Make the AI Write Failing Tests First

An agent can write implementation and tests that agree with the same mistaken assumption. Writing and reviewing the failing tests first separates the behavioral contract from the code that must satisfy it.

When to use

  • A rule has crisp edge cases such as expiry, reuse or authorization.
  • You are fixing a regression and can reproduce it as a test.
  • You want to stop an agent from weakening tests to make its implementation pass.

Example

Specify that a reset token expires after 30 minutes and works once. Confirm both tests fail, commit them, then let the agent change only production code.

TL;DR

Tests first, confirm they fail, commit them, then forbid the agent from editing them.

prompt
Write tests for the behavior below. Do not implement. Run them and confirm they fail.

Steps

  1. 1

    Tests only

    Describe behavior and edge cases, name the destination test file, and explicitly forbid placeholder implementations so the first run proves the tests can fail.

    prompt
    We are doing TDD. Write tests in src/auth/reset.test.ts for:
    - token expires after 30 minutes
    - token works once
    Do not create mock implementations. Run the tests and confirm they fail.
  2. 2

    Lock them in a commit

    Review the failures yourself, then commit the accepted tests as a stable boundary before implementation starts.

    bash
    git add src/auth/reset.test.ts
    git commit -m "test(auth): reset token rules"
  3. 3

    Implement

    Give the agent one constraint that matters most: production code may change, but the approved tests may not.

    prompt
    Make the tests pass. Do not modify any test file. Run tests until green.
  4. 4

    Verify the tests were not touched

    Compare test files against the tests-only commit; an empty result confirms implementation did not rewrite the contract.

    bash
    git diff HEAD~1 --stat -- '*.test.ts'

Gotchas

  • Agents love editing tests to pass; the commit + diff check catches it.
  • A test that passed before implementation tests nothing.
  • Ask for edge cases explicitly: expiry, reuse, wrong user.
  • Review the tests yourself before step 3; they are the spec.

Cheat sheet

1. TestsWrite, run, see red
2. CommitFreeze the tests
3. ImplementNo test edits allowed
4. Verifygit diff on test files

Related

Sources

Reviewing agent output? CodeCrab reviews pull requests locally with your own AI tools.