CC-301h · Module 2

TDD with Claude Code

4 min read

Test-driven development with Claude Code inverts the usual AI workflow. Instead of "write the function, then write tests," you write the tests first and then tell Claude to make them pass. This is powerful because the tests become the specification. You define exactly what the function should do through test cases, and Claude implements a function that satisfies every case.

The workflow: you write (or have Claude write) the test file first, with all the behaviors you want to validate. You run the tests — they all fail (red). You tell Claude: "Implement the function in src/utils/pricing.ts that makes all these tests pass." Claude reads the tests, infers the required behavior, and writes the implementation. You run the tests — they pass (green). You then review the implementation and ask Claude to refactor if needed, with the tests as a safety net.

  1. Red: Write Tests First Define the function's contract through test cases. Cover happy path, edge cases, and error conditions. Run the tests — they should all fail because the implementation does not exist yet. The failing tests are your specification.
  2. Green: Claude Implements "Make all tests in pricing.test.ts pass. Do not modify the test file." Claude reads the tests, infers the contract, and writes the minimal implementation. Run tests — they pass. The constraint "do not modify the test file" is critical.
  3. Refactor: Claude Cleans Up "Refactor the implementation for clarity and performance. Do not break any tests." Claude improves the code with the test suite as a safety net. Every refactoring step is validated against the tests.