Test-Driven Development (TDD): make Claude write the failing test first

by obra · MIT license · ★ 289,792 on GitHub · updated Sep 20

Test-Driven Development (TDD) cover

Test-Driven Development (TDD) is a free Claude skill by obra, part of the Superpowers collection. It holds Claude to red, green, refactor on every feature and bug fix: write one failing test, watch it fail, then write the minimum code to pass. Code written before its test gets deleted, not kept as a reference.

---
name: test-driven-development
description: Use when implementing any feature or bugfix, before writing implementation code
---

# Test-Driven Development (TDD)

## Overview

Write the test first. Watch it fail. Write minimal code to pass.

**Core principle:** If you didn't watch the test fail, you don't know if it tests the right thing.

**Violating the letter of the rules is violating the spirit of the rules.**

## When to Use

**Always:**

Overview

Write the test first. Watch it fail. Write minimal code to pass.

The SKILL.md below is the copy AgentAlley read and checked. The repo has changed it since; the other files are from commit 5bf4e78.

Manual install (npx, ZIP)
Claude Codenpx skills add obra/superpowers --skill test-driven-development -g -a claude-code
Claude Code (manual)mkdir -p ~/.claude/skills && curl -sL https://codeload.github.com/obra/superpowers/tar.gz/5bf4e7801107 \ | tar -xz -C ~/.claude/skills --strip-components=2 superpowers-5bf4e7801107/skills/test-driven-development
Windows (PowerShell)New-Item -ItemType Directory -Force "$HOME\.claude\skills" | Out-Null; Invoke-WebRequest "https://m.agentalley.io/zip/a9c8aee1a6ac7c7a0831/test-driven-development.zip" -OutFile "$env:TEMP\test-driven-development.zip"; Expand-Archive "$env:TEMP\test-driven-development.zip" -DestinationPath "$HOME\.claude\skills" -Force
Claude.ai / desktopDownload the ZIP and upload it under Settings → Capabilities → Skills.
Codex, Cursor, other agentsPoint them at SKILL.md. The other files are plain text.

Connects with Agent Alley MCP · agentalley.io/mcp

Files included

  • SKILL.md9.4 KB
  • writing-good-tests.md8.1 KB
Read the files here
obra/5bf4e782 files
SKILL.md
Show the full text321 lines

Test-Driven Development (TDD)

Overview

Write the test first. Watch it fail. Write minimal code to pass.

Core principle: If you didn't watch the test fail, you don't know if it tests the right thing.

Violating the letter of the rules is violating the spirit of the rules.

When to Use

Always:

  • New features
  • Bug fixes
  • Refactoring
  • Behavior changes

Exceptions (ask your human partner):

  • Throwaway prototypes
  • Generated code
  • Configuration files

Thinking "skip TDD just this once"? Stop. That's rationalization.

The Iron Law

NO PRODUCTION CODE WITHOUT A FAILING TEST FIRST

Write code before the test? Delete it. Start over.

No exceptions:

  • Don't keep it as "reference"
  • Don't "adapt" it while writing tests
  • Don't look at it
  • Delete means delete

Implement fresh from tests. Period.

Red-Green-Refactor

digraph tdd_cycle {
    rankdir=LR;
    red [label="RED\nWrite failing test", shape=box, style=filled, fillcolor="#ffcccc"];
    verify_red [label="Verify fails\ncorrectly", shape=diamond];
    green [label="GREEN\nMinimal code", shape=box, style=filled, fillcolor="#ccffcc"];
    verify_green [label="Verify passes\nAll green", shape=diamond];
    refactor [label="REFACTOR\nClean up", shape=box, style=filled, fillcolor="#ccccff"];
    next [label="Next", shape=ellipse];

    red -> verify_red;
    verify_red -> green [label="yes"];
    verify_red -> red [label="wrong\nfailure"];
    green -> verify_green;
    verify_green -> refactor [label="yes"];
    verify_green -> green [label="no"];
    refactor -> verify_green [label="stay\ngreen"];
    verify_green -> next;
    next -> red;
}
RED - Write Failing Test

Write one minimal test showing what should happen.

<Good> ```typescript test('retries failed operations 3 times', async () => { let attempts = 0; const operation = () => { attempts++; if (attempts < 3) throw new Error('fail'); return 'success'; };

const result = await retryOperation(operation);

expect(result).toBe('success'); expect(attempts).toBe(3); });

Clear name, tests real behavior, one thing
</Good>

<Bad>
```typescript
test('retry works', async () => {
  const mock = jest.fn()
    .mockRejectedValueOnce(new Error())
    .mockRejectedValueOnce(new Error())
    .mockResolvedValueOnce('success');
  await retryOperation(mock);
  expect(mock).toHaveBeenCalledTimes(3);
});

Vague name, tests mock not code </Bad>

Requirements:

  • One behavior
  • Clear name
  • Real code (no mocks unless unavoidable)
Verify RED - Watch It Fail

MANDATORY. Never skip.

npm test path/to/test.test.ts

Confirm:

  • Test fails (not errors)
  • Failure message is expected
  • Fails because feature missing (not typos)

Test passes? You're testing existing behavior. Fix test.

Test errors? Fix error, re-run until it fails correctly.

GREEN - Minimal Code

Write simplest code to pass the test.

<Good> ```typescript async function retryOperation<T>(fn: () => Promise<T>): Promise<T> { for (let i = 0; i < 3; i++) { try { return await fn(); } catch (e) { if (i === 2) throw e; } } throw new Error('unreachable'); } ``` Just enough to pass </Good><Bad> ```typescript async function retryOperation<T>( fn: () => Promise<T>, options?: { maxRetries?: number; backoff?: 'linear' | 'exponential'; onRetry?: (attempt: number) => void; } ): Promise<T> { // YAGNI } ``` Over-engineered </Bad>

Don't add features, refactor other code, or "improve" beyond the test.

Verify GREEN - Watch It Pass

MANDATORY.

npm test path/to/test.test.ts

Confirm:

  • Test passes
  • Other tests still pass
  • Output pristine (no errors, warnings)

Test fails? Fix code, not test.

Other tests fail? Fix now.

REFACTOR - Clean Up

After green only:

  • Remove duplication
  • Improve names
  • Extract helpers

Keep tests green. Don't add behavior.

Repeat

Next failing test for next feature.

Good Tests

Quality Good Bad
Minimal One thing. "and" in name? Split it. test('validates email and domain and whitespace')
Clear Name describes behavior test('test1')
Shows intent Demonstrates desired API Obscures what code should do

When writing or changing any test, read writing-good-tests.md for the rules that keep tests honest:

  • Name the production change that would make the test fail — before writing it
  • Assert on real behavior, never on mock behavior
  • Keep test-only code in test utilities, out of production classes
  • Understand a dependency's side effects before mocking it

Common Rationalizations

Excuse Reality
"Too simple to test" Simple code breaks. Test takes 30 seconds.
"I'll test after" Tests written after pass immediately — which proves nothing. They may test the wrong thing, test the implementation instead of the behavior, or miss the edge case you forgot. You never watched it fail, so you never proved it can catch the bug. Test-first forces that failure.
"Tests after achieve same goals (spirit not ritual)" Tests-after answer "what does this do?"; tests-first answer "what should this do?" Tests written after are biased by the code you already wrote — you verify the cases you remembered, not the ones you'd have discovered. Coverage without proof the tests work.
"Already manually tested" Manual testing is ad-hoc: no record of what you covered, no way to re-run it when the code changes, easy to forget cases under pressure. "Worked when I tried it" ≠ comprehensive. Automated tests run the same way every time.
"Deleting X hours is wasteful" Sunk cost fallacy — that time is already spent either way. The real choice: rewrite with TDD (high confidence) vs. keep it and bolt tests on after (low confidence, likely bugs). Keeping code you can't trust is the waste.
"Keep as reference, write tests first" You'll adapt it. That's testing after. Delete means delete.
"Need to explore first" Fine. Throw away exploration, start with TDD.
"Test hard = design unclear" Listen to test. Hard to test = hard to use.
"TDD will slow me down" TDD IS the pragmatic path: catches bugs before commit, prevents regressions, lets you refactor without fear. "Pragmatic" shortcuts mean debugging in production — slower, not faster.
"Manual test faster" Manual doesn't prove edge cases. You'll re-test every change.
"Existing code has no tests" You're improving it. Add tests for existing code.

Red Flags - STOP and Start Over

  • Code before test
  • Test after implementation
  • Test passes immediately
  • Can't explain why test failed
  • Tests added "later"
  • Rationalizing "just this once"
  • "I already manually tested it"
  • "Tests after achieve the same purpose"
  • "It's about spirit not ritual"
  • "Keep as reference" or "adapt existing code"
  • "Already spent X hours, deleting is wasteful"
  • "TDD is dogmatic, I'm being pragmatic"
  • "This is different because..."

All of these mean: Delete code. Start over with TDD.

Example: Bug Fix

Bug: Empty email accepted

RED

test('rejects empty email', async () => {
  const result = await submitForm({ email: '' });
  expect(result.error).toBe('Email required');
});

Verify RED

$ npm test
FAIL: expected 'Email required', got undefined

GREEN

function submitForm(data: FormData) {
  if (!data.email?.trim()) {
    return { error: 'Email required' };
  }
  // ...
}

Verify GREEN

$ npm test
PASS

REFACTOR Extract validation for multiple fields if needed.

Verification Checklist

Before marking work complete:

  • Every new function/method has a test
  • Watched each test fail before implementing
  • Each test failed for expected reason (feature missing, not typo)
  • Wrote minimal code to pass each test
  • All tests pass
  • Output pristine (no errors, warnings)
  • Tests use real code (mocks only if unavoidable)
  • Edge cases and errors covered

Can't check all boxes? You skipped TDD. Start over.

When Stuck

Problem Solution
Don't know how to test Write wished-for API. Write assertion first. Ask your human partner.
Test too complicated Design too complicated. Simplify interface.
Must mock everything Code too coupled. Use dependency injection.
Test setup huge Extract helpers. Still complex? Simplify design.

Debugging Integration

Bug found? Write failing test reproducing it. Follow TDD cycle. Test proves fix and prevents regression.

Never fix bugs without a test.

Final Rule

Production code → test exists and failed first
Otherwise → not TDD

No exceptions without your human partner's permission.

1---
2name: test-driven-development
3description: Use when implementing any feature or bugfix, before writing implementation code
4---
5 
6# Test-Driven Development (TDD)
7 
8## Overview
9 
10Write the test first. Watch it fail. Write minimal code to pass.
11 
12**Core principle:** If you didn't watch the test fail, you don't know if it tests the right thing.
13 
14**Violating the letter of the rules is violating the spirit of the rules.**
15 
16## When to Use
17 
18**Always:**
19- New features
20- Bug fixes
21- Refactoring
22- Behavior changes
23 
24**Exceptions (ask your human partner):**
25- Throwaway prototypes
26- Generated code
27- Configuration files
28 
29Thinking "skip TDD just this once"? Stop. That's rationalization.
30 
31## The Iron Law
32 
33```
34NO PRODUCTION CODE WITHOUT A FAILING TEST FIRST
35```
36 
37Write code before the test? Delete it. Start over.
38 
39**No exceptions:**
40- Don't keep it as "reference"
41- Don't "adapt" it while writing tests
42- Don't look at it
43- Delete means delete
44 
45Implement fresh from tests. Period.
46 
47## Red-Green-Refactor
48 
49```dot
50digraph tdd_cycle {
51 rankdir=LR;
52 red [label="RED\nWrite failing test", shape=box, style=filled, fillcolor="#ffcccc"];
53 verify_red [label="Verify fails\ncorrectly", shape=diamond];
54 green [label="GREEN\nMinimal code", shape=box, style=filled, fillcolor="#ccffcc"];
55 verify_green [label="Verify passes\nAll green", shape=diamond];
56 refactor [label="REFACTOR\nClean up", shape=box, style=filled, fillcolor="#ccccff"];
57 next [label="Next", shape=ellipse];
58 
59 red -> verify_red;
60 verify_red -> green [label="yes"];
61 verify_red -> red [label="wrong\nfailure"];
62 green -> verify_green;
63 verify_green -> refactor [label="yes"];
64 verify_green -> green [label="no"];
65 refactor -> verify_green [label="stay\ngreen"];
66 verify_green -> next;
67 next -> red;
68}
69```
70 
71### RED - Write Failing Test
72 
73Write one minimal test showing what should happen.
74 
75<Good>
76```typescript
77test('retries failed operations 3 times', async () => {
78 let attempts = 0;
79 const operation = () => {
80 attempts++;
81 if (attempts < 3) throw new Error('fail');
82 return 'success';
83 };
84 
85 const result = await retryOperation(operation);
86 
87 expect(result).toBe('success');
88 expect(attempts).toBe(3);
89});
90```
91Clear name, tests real behavior, one thing
92</Good>
93 
94<Bad>
95```typescript
96test('retry works', async () => {
97 const mock = jest.fn()
98 .mockRejectedValueOnce(new Error())
99 .mockRejectedValueOnce(new Error())
100 .mockResolvedValueOnce('success');
101 await retryOperation(mock);
102 expect(mock).toHaveBeenCalledTimes(3);
103});
104```
105Vague name, tests mock not code
106</Bad>
107 
108**Requirements:**
109- One behavior
110- Clear name
111- Real code (no mocks unless unavoidable)
112 
113### Verify RED - Watch It Fail
114 
115**MANDATORY. Never skip.**
116 
117```bash
118npm test path/to/test.test.ts
119```
120 
121Confirm:
122- Test fails (not errors)
123- Failure message is expected
124- Fails because feature missing (not typos)
125 
126**Test passes?** You're testing existing behavior. Fix test.
127 
128**Test errors?** Fix error, re-run until it fails correctly.
129 
130### GREEN - Minimal Code
131 
132Write simplest code to pass the test.
133 
134<Good>
135```typescript
136async function retryOperation<T>(fn: () => Promise<T>): Promise<T> {
137 for (let i = 0; i < 3; i++) {
138 try {
139 return await fn();
140 } catch (e) {
141 if (i === 2) throw e;
142 }
143 }
144 throw new Error('unreachable');
145}
146```
147Just enough to pass
148</Good>
149 
150<Bad>
151```typescript
152async function retryOperation<T>(
153 fn: () => Promise<T>,
154 options?: {
155 maxRetries?: number;
156 backoff?: 'linear' | 'exponential';
157 onRetry?: (attempt: number) => void;
158 }
159): Promise<T> {
160 // YAGNI
161}
162```
163Over-engineered
164</Bad>
165 
166Don't add features, refactor other code, or "improve" beyond the test.
167 
168### Verify GREEN - Watch It Pass
169 
170**MANDATORY.**
171 
172```bash
173npm test path/to/test.test.ts
174```
175 
176Confirm:
177- Test passes
178- Other tests still pass
179- Output pristine (no errors, warnings)
180 
181**Test fails?** Fix code, not test.
182 
183**Other tests fail?** Fix now.
184 
185### REFACTOR - Clean Up
186 
187After green only:
188- Remove duplication
189- Improve names
190- Extract helpers
191 
192Keep tests green. Don't add behavior.
193 
194### Repeat
195 
196Next failing test for next feature.
197 
198## Good Tests
199 
200| Quality | Good | Bad |
201|---------|------|-----|
202| **Minimal** | One thing. "and" in name? Split it. | `test('validates email and domain and whitespace')` |
203| **Clear** | Name describes behavior | `test('test1')` |
204| **Shows intent** | Demonstrates desired API | Obscures what code should do |
205 
206When writing or changing any test, read [writing-good-tests.md](writing-good-tests.md) for the rules that keep tests honest:
207- Name the production change that would make the test fail — before writing it
208- Assert on real behavior, never on mock behavior
209- Keep test-only code in test utilities, out of production classes
210- Understand a dependency's side effects before mocking it
211 
212## Common Rationalizations
213 
214| Excuse | Reality |
215|--------|---------|
216| "Too simple to test" | Simple code breaks. Test takes 30 seconds. |
217| "I'll test after" | Tests written after pass immediately — which proves nothing. They may test the wrong thing, test the implementation instead of the behavior, or miss the edge case you forgot. You never watched it fail, so you never proved it can catch the bug. Test-first forces that failure. |
218| "Tests after achieve same goals (spirit not ritual)" | Tests-after answer "what does this do?"; tests-first answer "what should this do?" Tests written after are biased by the code you already wrote — you verify the cases you remembered, not the ones you'd have discovered. Coverage without proof the tests work. |
219| "Already manually tested" | Manual testing is ad-hoc: no record of what you covered, no way to re-run it when the code changes, easy to forget cases under pressure. "Worked when I tried it" ≠ comprehensive. Automated tests run the same way every time. |
220| "Deleting X hours is wasteful" | Sunk cost fallacy — that time is already spent either way. The real choice: rewrite with TDD (high confidence) vs. keep it and bolt tests on after (low confidence, likely bugs). Keeping code you can't trust is the waste. |
221| "Keep as reference, write tests first" | You'll adapt it. That's testing after. Delete means delete. |
222| "Need to explore first" | Fine. Throw away exploration, start with TDD. |
223| "Test hard = design unclear" | Listen to test. Hard to test = hard to use. |
224| "TDD will slow me down" | TDD IS the pragmatic path: catches bugs before commit, prevents regressions, lets you refactor without fear. "Pragmatic" shortcuts mean debugging in production — slower, not faster. |
225| "Manual test faster" | Manual doesn't prove edge cases. You'll re-test every change. |
226| "Existing code has no tests" | You're improving it. Add tests for existing code. |
227 
228## Red Flags - STOP and Start Over
229 
230- Code before test
231- Test after implementation
232- Test passes immediately
233- Can't explain why test failed
234- Tests added "later"
235- Rationalizing "just this once"
236- "I already manually tested it"
237- "Tests after achieve the same purpose"
238- "It's about spirit not ritual"
239- "Keep as reference" or "adapt existing code"
240- "Already spent X hours, deleting is wasteful"
241- "TDD is dogmatic, I'm being pragmatic"
242- "This is different because..."
243 
244**All of these mean: Delete code. Start over with TDD.**
245 
246## Example: Bug Fix
247 
248**Bug:** Empty email accepted
249 
250**RED**
251```typescript
252test('rejects empty email', async () => {
253 const result = await submitForm({ email: '' });
254 expect(result.error).toBe('Email required');
255});
256```
257 
258**Verify RED**
259```bash
260$ npm test
261FAIL: expected 'Email required', got undefined
262```
263 
264**GREEN**
265```typescript
266function submitForm(data: FormData) {
267 if (!data.email?.trim()) {
268 return { error: 'Email required' };
269 }
270 // ...
271}
272```
273 
274**Verify GREEN**
275```bash
276$ npm test
277PASS
278```
279 
280**REFACTOR**
281Extract validation for multiple fields if needed.
282 
283## Verification Checklist
284 
285Before marking work complete:
286 
287- [ ] Every new function/method has a test
288- [ ] Watched each test fail before implementing
289- [ ] Each test failed for expected reason (feature missing, not typo)
290- [ ] Wrote minimal code to pass each test
291- [ ] All tests pass
292- [ ] Output pristine (no errors, warnings)
293- [ ] Tests use real code (mocks only if unavoidable)
294- [ ] Edge cases and errors covered
295 
296Can't check all boxes? You skipped TDD. Start over.
297 
298## When Stuck
299 
300| Problem | Solution |
301|---------|----------|
302| Don't know how to test | Write wished-for API. Write assertion first. Ask your human partner. |
303| Test too complicated | Design too complicated. Simplify interface. |
304| Must mock everything | Code too coupled. Use dependency injection. |
305| Test setup huge | Extract helpers. Still complex? Simplify design. |
306 
307## Debugging Integration
308 
309Bug found? Write failing test reproducing it. Follow TDD cycle. Test proves fix and prevents regression.
310 
311Never fix bugs without a test.
312 
313## Final Rule
314 
315```
316Production code → test exists and failed first
317Otherwise → not TDD
318```
319 
320No exceptions without your human partner's permission.
321 
View all files on GitHub →

Details

Updated
Sep 20, 2026
License
MIT
Stars on the repo
★ 289,792
Checked
Source
obra/superpowers ↗
Creator
obra · 14 listings
View creator

Similar skills

See all →
Skill29 production-ready scripts for iOS app testing, buildingIos simulator skillconorluddy/ios-simulator-skill · by conorluddy29 production-ready scripts for iOS app testing, building, and automation. Provides semantic UI navigation, build automation, accessibility testing, and simulator lifecycle management. Optimized for AI agents with minimal token output.★ 1.3k GitHub starsSkillMoAI unified orchestrator for autonomous developmentmodu-ai/moai-adk · by modu-aiMoAI unified orchestrator for autonomous development. Routes natural language or subcommands (plan, run, sync, project, fix, loop, mx, feedback, review, clean, codemaps, gate, e2e, harness, goal, gtd, todo) to specialized agents.★ 1.2k GitHub starsSkillWrite Android unit, Compose UI, and Hilt-integrated testsAndroid Testing StandardsHoangNguyen0403/agent-skills-standard · by HoangNguyen0403Write Android unit, Compose UI, and Hilt-integrated tests. Use when designing test behavior with MockK or coroutine test utilities; defer database/WorkManager-specific recipes to the owning feature skill.★ 569 GitHub starsSkillToolkit for interacting with and testing local webWebapp testinganthropics/skills · by anthropicsToolkit for interacting with and testing local web applications using Playwright. Supports verifying frontend functionality, debugging UI behavior, capturing browser screenshots, and viewing browser logs.★ 178k GitHub starsPromptGuide to fixing bugs using a test-first approachTest first bug fixing approachf/prompts.chat · by Ilker UlusoyGuide to fixing bugs using a test-first approach, ensuring code reliability through systematic testing and implementation.New listingPromptToolkit for interacting with and testing local webWeb application testing skillf/prompts.chat · by Fatih Kadir AkınToolkit for interacting with and testing local web applications using Playwright. Supports verifying frontend functionality, debugging UI behavior, capturing browser screenshots, and viewing browser logs.New listing

More from obra

SkillBrainstorms ideas into designs before any creative workBrainstorming Ideas Into Designsobra/superpowers · by obraYou MUST use this before any creative work - creating features, building components, adding functionality, or modifying behavior. Explores user intent, requirements and design before implementation.★ 290k GitHub starsSkillRequires technical rigor and verificationCode Review Receptionobra/superpowers · by obraUse when receiving code review feedback, before implementing suggestions, especially if feedback seems unclear or technically questionable - requires technical rigor and verification, not performative agreement or blind implementation★ 290k GitHub starsSkillDispatches parallel agentsDispatching parallel agentsobra/superpowers · by obraUse when facing 2+ independent tasks that can be worked on without shared state or sequential dependencies★ 290k GitHub starsSkillExecutes plans with review checkpointsExecuting plansobra/superpowers · by obraUse when you have a written implementation plan to execute in a separate session with review checkpoints★ 290k GitHub starsSkillFinishes a development branchFinishing a development branchobra/superpowers · by obraUse when implementation is complete, all tests pass, and you need to decide how to integrate the work★ 290k GitHub starsSkillRequests code review before mergingRequesting code reviewobra/superpowers · by obraUse when completing tasks, implementing major features, or before merging to verify work meets requirements★ 290k GitHub stars