Test-Driven Development

Test-Driven Development

Enforces strict test-first development for features and bugfixes with a red-green-refactor cycle and no production code without a failing test.

Skill files2 files
SKILL.md331 lines
1
---
2
name: test-driven-development
3
description: Use when implementing any feature or bugfix, before writing implementation code
4
---
5
6
# Test-Driven Development (TDD)
7
8
## Overview
9
10
Write 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
29
Thinking "skip TDD just this once"? Stop. That's rationalization.
30
31
## The Iron Law
32
33
```
34
NO PRODUCTION CODE WITHOUT A FAILING TEST FIRST
35
```
36
37
Write 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
45
Implement fresh from tests. Period.
46
47
## Red-Green-Refactor
48
49
```dot
50
digraph 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
73
Write one minimal test showing what should happen.
74
75
<Good>
76
```typescript
77
test('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
```
91
Clear name, tests real behavior, one thing
92
</Good>
93
94
<Bad>
95
```typescript
96
test('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
```
105
Vague 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
118
npm test path/to/test.test.ts
119
```
120
121
Confirm:
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
132
Write simplest code to pass the test.
133
134
<Good>
135
```typescript
136
async 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
```
147
Just enough to pass
148
</Good>
149
150
<Bad>
151
```typescript
152
async 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
```
163
Over-engineered
164
</Bad>
165
166
Don't add features, refactor other code, or "improve" beyond the test.
167
168
### Verify GREEN - Watch It Pass
169
170
**MANDATORY.**
171
172
```bash
173
npm test path/to/test.test.ts
174
```
175
176
Confirm:
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
**"Other tests" means the project's suite, not just your file.** A
186
green run of the test you wrote is not a green suite. Before you call
187
the change done, run the project's test command (bare `pytest`,
188
`npm test`, `cargo test` — whatever the repo uses) even when your task
189
named only one test file. A scope statement in your task bounds the
190
deliverable, not your verification. Any failure that run shows —
191
including one you didn't cause — goes in your report by name; a red
192
test you watched scroll past and didn't mention is a report falsified
193
by omission.
194
195
### REFACTOR - Clean Up
196
197
After green only:
198
- Remove duplication
199
- Improve names
200
- Extract helpers
201
202
Keep tests green. Don't add behavior.
203
204
### Repeat
205
206
Next failing test for next feature.
207
208
## Good Tests
209
210
| Quality | Good | Bad |
211
|---------|------|-----|
212
| **Minimal** | One thing. "and" in name? Split it. | `test('validates email and domain and whitespace')` |
213
| **Clear** | Name describes behavior | `test('test1')` |
214
| **Shows intent** | Demonstrates desired API | Obscures what code should do |
215
216
When writing or changing any test, read [writing-good-tests.md](writing-good-tests.md) for the rules that keep tests honest:
217
- Name the production change that would make the test fail — before writing it
218
- Assert on real behavior, never on mock behavior
219
- Keep test-only code in test utilities, out of production classes
220
- Understand a dependency's side effects before mocking it
221
222
## Common Rationalizations
223
224
| Excuse | Reality |
225
|--------|---------|
226
| "Too simple to test" | Simple code breaks. Test takes 30 seconds. |
227
| "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. |
228
| "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. |
229
| "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. |
230
| "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. |
231
| "Keep as reference, write tests first" | You'll adapt it. That's testing after. Delete means delete. |
232
| "Need to explore first" | Fine. Throw away exploration, start with TDD. |
233
| "Test hard = design unclear" | Listen to test. Hard to test = hard to use. |
234
| "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. |
235
| "Manual test faster" | Manual doesn't prove edge cases. You'll re-test every change. |
236
| "Existing code has no tests" | You're improving it. Add tests for existing code. |
237
238
## Red Flags - STOP and Start Over
239
240
- Code before test
241
- Test after implementation
242
- Test passes immediately
243
- Can't explain why test failed
244
- Tests added "later"
245
- Rationalizing "just this once"
246
- "I already manually tested it"
247
- "Tests after achieve the same purpose"
248
- "It's about spirit not ritual"
249
- "Keep as reference" or "adapt existing code"
250
- "Already spent X hours, deleting is wasteful"
251
- "TDD is dogmatic, I'm being pragmatic"
252
- "This is different because..."
253
254
**All of these mean: Delete code. Start over with TDD.**
255
256
## Example: Bug Fix
257
258
**Bug:** Empty email accepted
259
260
**RED**
261
```typescript
262
test('rejects empty email', async () => {
263
const result = await submitForm({ email: '' });
264
expect(result.error).toBe('Email required');
265
});
266
```
267
268
**Verify RED**
269
```bash
270
$ npm test
271
FAIL: expected 'Email required', got undefined
272
```
273
274
**GREEN**
275
```typescript
276
function submitForm(data: FormData) {
277
if (!data.email?.trim()) {
278
return { error: 'Email required' };
279
}
280
// ...
281
}
282
```
283
284
**Verify GREEN**
285
```bash
286
$ npm test
287
PASS
288
```
289
290
**REFACTOR**
291
Extract validation for multiple fields if needed.
292
293
## Verification Checklist
294
295
Before marking work complete:
296
297
- [ ] Every new function/method has a test
298
- [ ] Watched each test fail before implementing
299
- [ ] Each test failed for expected reason (feature missing, not typo)
300
- [ ] Wrote minimal code to pass each test
301
- [ ] All tests pass
302
- [ ] Output pristine (no errors, warnings)
303
- [ ] Tests use real code (mocks only if unavoidable)
304
- [ ] Edge cases and errors covered
305
306
Can't check all boxes? You skipped TDD. Start over.
307
308
## When Stuck
309
310
| Problem | Solution |
311
|---------|----------|
312
| Don't know how to test | Write wished-for API. Write assertion first. Ask your human partner. |
313
| Test too complicated | Design too complicated. Simplify interface. |
314
| Must mock everything | Code too coupled. Use dependency injection. |
315
| Test setup huge | Extract helpers. Still complex? Simplify design. |
316
317
## Debugging Integration
318
319
Bug found? Write failing test reproducing it. Follow TDD cycle. Test proves fix and prevents regression.
320
321
Never fix bugs without a test.
322
323
## Final Rule
324
325
```
326
Production code → test exists and failed first
327
Otherwise → not TDD
328
```
329
330
No exceptions without your human partner's permission.
331

© Jesse Vincent · MIT · source · posted by @OpenSourceBuffGuy on promptparty.com

@OpenSourceBuffGuy

I find openly licensed prompts and post them here.

0 followers · 6,373 prompts

More by @OpenSourceBuffGuy

See all
Website Clone Architect prompt image

Website Clone Architect

Reverse-engineers a website section by section, writes component specs, and hands them to parallel builder agents in git worktrees to rebuild it.

agent-skill, orchestrator, parallel-agents, multi-agent, plan-then-execute, web-development, frontend, codebase-analysis, scaffolding, css, html, nextjs, typescript, git, mcp, claude-code, for-developers, for-designers, long-form, advanced, technical-spec, task-decomposition, structured-output, design-systems, ui-ux, tool-use, checklist, report, vibe-coding

Italian Terrace Cafe Candid Portrait prompt image

Italian Terrace Cafe Candid Portrait

Generates a photorealistic candid shot of a woman in a white corset dress laughing at a sunny hotel terrace cafe, written as detailed JSON.

image-prompt, json-prompt, structured-output, photorealistic, portrait, woman, candid, fashion, cottagecore, natural-light, golden-hour, bokeh, summer, travel, cityscape, mountains, medium-shot, vibrant-colors, for-photographers, nano-banana, fashion-shoot, luxury

Night Street Photo With Leashed Cat prompt image

Night Street Photo With Leashed Cat

Generates a flash-lit night street photo of a blonde woman in a retro track jacket walking a hissing tabby cat on a leash.

image-prompt, json-prompt, nano-banana, structured-output, portrait, woman, animals, pet-portrait, night-scene, street-photography, candid, editorial, fashion, dramatic-lighting, photorealistic, vertical-format, medium-shot, graffiti, for-photographers, for-content-creators

1 view

Reviews

Loading reviews…

Discussion

Loading comments…