Skills · Content & docs

Test-Driven Development (TDD)

Unverified30/40

Use when implementing any feature or bugfix, before writing implementation code

Originally by obra · MIT

Claude CodePartialHas SKILL.md but declares no allowed-tools — Claude Code will ask for permission each time
Cursor·UnknownWe have not crawled the repo tree, so we will not guess
Codex·UnknownWe have not crawled the repo tree, so we will not guess
Gemini CLI·UnknownThe spec defines no detection rule for Gemini
Copilot·UnknownWe have not crawled the repo tree, so we will not guess
npx agentalley add test-driven-development

This command does not work yet — the CLI is still being built. Until then, use Raw in the reader below to take the file.

Who is stuck, and on what

Use when implementing any feature or bugfix, before writing implementation code

The whole source

No sign-in, no blur, nothing truncated
test-driven-development/SKILL.md321 lines8.8 KBRawView on GitHub
Frontmatter — 2 properties
nametest-driven-development
descriptionUse when implementing any feature or bugfix, before writing implementation code
1---
2name: test-driven-development
3description: Use when implementing any feature or bugfix, before writing implementation code
4---A5No allowed-tools declared — no way to tell what this skill may touch
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 

Reviews

Installed this one?Write the first review and take the Trailblazer badge.

Reviews only open after a real install, so this is empty — and we leave it empty rather than invent one.

Alternatives

Also in Content & docs