Skip to main content

Someone wanted to learn this too, so Grasp built them a personal learning path.

You can keep exploring this one or create your own

TDD Prompting for Claude Code

Welcome back! In our last lesson, you learned how to prompt Claude Code to generate comprehensive unit and integration tests for existing FastAPI code. This skill is crucial for improving code quality and test coverage.

Today, we'll build on that by exploring a more disciplined and powerful software development methodology: Test-Driven Development (TDD). Instead of writing tests after the code is written, we'll write the tests first.

The learning outcome for this lesson is to define a structured prompt that instructs Claude Code to write implementation code based on a provided failing test. This is the heart of the TDD workflow and a technique that significantly enhances the reliability of AI-generated code, a vital consideration for the production-grade systems you build.

The Red-Green-Refactor Cycle

Test-Driven Development is built around a short, repetitive cycle:

  1. RED: Write a single automated test for a new piece of functionality. The test will fail because the functionality doesn't exist yet.
  2. GREEN: Write the absolute minimum amount of production code required to make the failing test pass.
  3. REFACTOR: Clean up and improve the design of the code you just wrote, ensuring all tests continue to pass.

This cycle provides a tight feedback loop that guides development. To understand this concept more deeply, let's watch a short introduction.

Red Green Refactor is OP With Claude Code

The video 'Red Green Refactor is OP With Claude Code' from Matt Pocock provides an excellent explanation of the TDD cycle and its origins.

Please watch the segment from the beginning until 01:52. Focus on the definition of the three phases: Red (failing test), Green (minimal passing code), and Refactor (cleanup).

Why TDD Is So Effective for AI Code Generation

You might be wondering why we should bother with this rigid process when we could just ask Claude to write the feature directly. The TDD cycle acts as a powerful set of guardrails for an AI agent.

When you provide a failing test, you give the AI a clear, unambiguous, and verifiable goal: "make this specific test pass." This constraint prevents the model from writing overly complex or incorrect code. It forces simplicity and correctness.

Let's continue with the same video to see why this is so valuable.

Red Green Refactor is OP With Claude Code

This next clip explains why the Red-Green-Refactor loop is particularly powerful when working with an AI coding agent like Claude Code.

Watch the section from 01:52 to 02:58. Pay attention to how the cycle provides a feedback mechanism that builds confidence in the AI's output without you needing to scrutinize every line of implementation.

As the video highlights, seeing the test go from red to green gives you high confidence that the AI has correctly implemented the specified behavior.

Structuring the "Green" Prompt

Our focus today is on the GREEN phase. We have a failing test, and now we need to instruct Claude to write the code that makes it pass. A good prompt for this step is critical. It must be explicit about the goal.

A simple but highly effective prompt is:

"Write the minimal implementation to pass the current failing test."

Let's look at a more formal definition of this workflow instruction.

Patience Is All You Need - Medium

The article 'Patience Is All You Need' on Medium details a developer's journey of refining their workflow with Claude. It contains an excellent, explicit template for a TDD cycle that can be placed in a CLAUDE.md file.

Read the section titled 'Required TDD Cycle'. Specifically, focus on the instructions for step '2. GREEN: Write minimal implementation'. Notice the key constraints: 'write only the minimal code' and 'No additional features'.

This structured instruction, whether given directly in a prompt or embedded in a CLAUDE.md file, is the key to successfully guiding Claude through the GREEN phase.

Formalizing TDD with Custom Slash Commands

Manually typing these instructions can become repetitive. As an advanced user, you can encapsulate these structured prompts into custom slash commands to streamline your workflow. Many developers have already created command packs for this purpose.

wbern/claude-instructions

This GitHub repository, 'wbern/claude-instructions', offers a pre-built set of slash commands for a TDD workflow in Claude Code. It's a perfect example of how to put our structured prompts into practice.

Please review the following parts of the README.md file: Introduction: Understand how custom commands like /red, /green, and /refactor work. 'Which Command Should I Use?': Look at the flowchart to see how these commands fit into the TDD workflow. 'Available Commands': Note the descriptions for /red, /green, /refactor, and /cycle.

The /green command in this pack is a perfect, reusable implementation of the structured prompt we're learning to define. When you type /green, you are instructing Claude to execute that predefined "minimal implementation" logic.

A Complete Red-to-Green Example

Let's see this in action. The following video demonstrates a full TDD cycle where Claude is prompted to implement a new feature.

AI Writes Better Code With Test Driven Development

In 'AI Writes Better Code With Test Driven Development' by Zen van Riel, Claude Code is used to add a 'buy it now' feature to an auction system using a strict TDD approach.

Watch the following sequence: Prompting and First Failing Tests (04:59 - 07:19): Observe how Claude is prompted with the TDD methodology and begins by generating the first failing tests. Confirming Failure (07:19 - 08:12): See how Claude runs the tests to confirm they fail as expected. Implementing and Passing (08:12 - 09:55): Watch as Claude writes the minimal code to make the tests pass and then confirms that all tests are now green.

This video provides a clear, practical demonstration of the entire RED-to-GREEN flow, showing how Claude first creates the failing tests, confirms their failure, and then proceeds to write just enough code to make them pass, precisely following the TDD methodology we've outlined.

Your Turn: Craft the "Green" Prompt

Now it's time to apply what you've learned. Imagine you are adding a feature to a FastAPI application that manages user profiles. The new requirement is to allow users to set a "status" message.

You have already written the following failing test in tests/test_users.py:




# tests/test_users.py
from fastapi.testclient import TestClient
from main import app  # Assuming your FastAPI app is in main.py

client = TestClient(app)

def test_update_user_status_success():



    # This user exists in our test setup
    user_id = "testuser123"
    



    # The new feature is to update the status
    response = client.put(
        f"/users/{user_id}/status",
        json={"status": "Working on advanced Claude Code features!"}
    )
    



    # Assertions for the new feature
    assert response.status_code == 200
    data = response.json()
    assert data["user_id"] == user_id
    assert data["status"] == "Working on advanced Claude Code features!"

def test_update_user_status_too_long():
    user_id = "testuser123"
    long_status = "a" * 151  # Status is limited to 150 characters
    
    response = client.put(
        f"/users/{user_id}/status",
        json={"status": long_status}
    )
    
    assert response.status_code == 400
    assert "Status must be 150 characters or less" in response.json()["detail"]

This test fails because the PUT /users/{user_id}/status endpoint and its associated logic do not exist.

Your project has the following structure and main.py file:

.
├── main.py
└── tests/
    └── test_users.py



# main.py
from fastapi import FastAPI, HTTPException
from pydantic import BaseModel, Field




# A dummy database for our example
fake_users_db = {"testuser123": {"username": "testuser123", "email": "test@example.com"}}

app = FastAPI()

class UserStatusUpdate(BaseModel):
    status: str = Field(..., max_length=150)




# The endpoint you need to implement is missing.
# ... your implementation will go here ...

Your Task:

Write the structured prompt you would give to Claude Code to implement the feature. Your prompt should instruct Claude to write the necessary FastAPI code in main.py to make the failing tests in tests/test_users.py pass.

Think about the key instructions:

  • What is the goal? (Make the tests pass).
  • What is the constraint? (Write minimal code).
  • What files are relevant context? (@main.py, @tests/test_users.py).

Conclusion

In this lesson, you've taken a significant step toward mastering professional, AI-assisted development. You now understand how to use the Test-Driven Development cycle to guide Claude Code, ensuring the features it builds are correct by design.

Key Takeaways:

  • TDD follows a Red-Green-Refactor cycle: failing test, minimal passing code, cleanup.
  • Providing a failing test gives the AI a clear, verifiable goal, which improves the quality and reliability of the generated code.
  • A structured prompt for the GREEN phase must explicitly instruct Claude to write the minimal code necessary to make the tests pass.
  • This process can be streamlined by creating reusable slash commands like /green.

Next Up:
You've now learned to generate tests for existing code (Lesson 5.1) and to generate code for existing tests (this lesson). In the next lesson, we will combine these skills. You will learn to execute a full TDD cycle, instructing Claude to write the failing test, then the passing code, and finally to refactor the result, all within a single, powerful workflow.

Can't find a good explanation? Sign up and we'll make it for you

Sign up