axiomantic/spellbook/test-driven-development

Claude Code and agent skill by axiomantic/spellbook

Trust tier 3
  • community
  • ext:[{"type":"hook","description":"Pre/post lifecycle hooks"}]
Source check pending

Checking that the SKILL.md file is still in the repository.

Use when user explicitly requests test-driven development. Triggers: 'TDD', 'write tests first', 'red green refactor', 'test-first', 'start with the test'. Also invoked by develop and executing-plans for implementation tasks. NOT for: full feature work (use develop, which includes TDD internally).

Install

npx vskill@latest install axiomantic/spellbook/test-driven-development

Semi-extensibleMentions customization, but needs skill-specific knowledge. Read the extensible skills standard

SKILL.md

The same SKILL.md was published earlier as axiomantic/spellbook/test-driven-development.

Test-Driven Development

<ROLE> Quality Engineer with zero-defect mindset. Reputation depends on shipping code that works, not code that "should work." </ROLE>

Invariant Principles

  1. Failure Proves Testing - Test passing immediately proves nothing. Only watching failure proves test detects what it claims.
  2. Order Creates Trust - Tests-first answer "what should this do?" Tests-after answer "what does this do?" Fundamentally different questions.
  3. Minimal Sufficiency - Write exactly enough code to pass. YAGNI violations compound into untested complexity.
  4. Deletion Over Adaptation - Code written before tests is contaminated. Keeping "as reference" means testing after. Delete means delete.

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

Inputs

InputRequiredDescription
Feature/bugfix descriptionYesWhat behavior to implement or fix
Existing test patternsNoProject's testing conventions and frameworks
API contractsNoExpected interface signatures

Outputs

OutputTypeDescription
Failing testFileTest demonstrating missing behavior
Minimal implementationFileCode passing the test
Test execution evidenceInlineObserved failure before green

When to Use

Always: new features, bug fixes, refactoring, behavior changes.

Exceptions (ask human partner; no human available? default: apply TDD):

  • Throwaway prototypes
  • Generated code
  • Configuration files

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

The Iron Law

NO PRODUCTION CODE WITHOUT FAILING TEST FIRST

Code before test? Delete. Start over. No "reference," no "adapting," no looking at it.

Reasoning Schema

<analysis> Before writing ANY code:

  • What behavior needs verification?
  • What assertion proves that behavior?
  • What's the simplest API shape?

</analysis>

<reflection> After EACH phase:

  • RED: Did test fail? Why? Expected failure mode?
  • GREEN: Minimal code? No extra features?
  • REFACTOR: Still green? Behavior unchanged?

</reflection>

Red-Green-Refactor

RED: Write Failing Test

One behavior. Clear name. Real code (mocks only if unavoidable; unavoidable = external I/O, time, hardware — not laziness).

<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>

Verify RED: Watch It Fail

MANDATORY. Never skip.

bash
npm test path/to/test.test.ts

Confirm:

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

Test passes? Testing existing behavior. Fix test. Test errors? Fix error, re-run until it fails correctly.

GREEN: Minimal Code

Simplest code to pass. No features, no refactoring, no "improvements."

Load the enforcing-code-quality skill before writing this code. "Minimal" bounds SCOPE, not quality: the prohibited patterns (any types, blanket try-catch, resource leaks, unvalidated non-null assertions) are not licensed by the fact that a test is currently red. A shortcut taken here survives REFACTOR, because REFACTOR only cleans what it recognizes as duplication.

<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>

Verify GREEN: Watch It Pass

MANDATORY.

bash
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.

Complete when: duplication removed, names clear, all tests still green, no new behavior added.

Repeat

Next failing test for next feature. The cycle continues until all behavior is implemented.

Good Tests

QualityGoodBad
MinimalOne thing. "and" in name? Split it.test('validates email and domain and whitespace')
ClearName describes behaviortest('test1')
Shows intentDemonstrates desired APIObscures what code should do
FastCompletes in <1s. No I/O or heavy fixtures in unit tests.5-second test with database setup for pure logic
Content-validatingAsserts exact values, full objects, every fieldassert len(result) > 0, assert result is not None

Assertion Quality

<CRITICAL>

The Full Assertion Principle

Every assertion MUST assert exact equality against the COMPLETE expected output. This applies to ALL output -- static, dynamic, or partially dynamic. There are no categories of output exempt from this rule.

python
# CORRECT: exact equality on complete static output
assert result == expected_complete_output
# CORRECT: exact equality with dynamically constructed expected value
assert message == f"Today's date is {datetime.date.today().isoformat()}"
# BANNED: partial assertion on any output -- dynamic content is no excuse
assert "substring" in result # Hides structural errors, missing content, extra garbage
assert datetime.date.today().isoformat() in message # Dynamic value is no excuse for partial check
assert "foo" in result and "bar" in result # Still partial, still BANNED
assert len(result) > 0 # Meaningless
# BANNED: mock.ANY hides argument values
mock_fn.assert_called_with(mock.ANY, mock.ANY)

ALL output demands complete verification: writers, serializers, formatters, code generators, query builders, template renderers, config builders, functions with dynamic content. For multi-line output, use triple-quoted strings or dedent helpers. Output length is NEVER a justification for partial assertions.

When output contains dynamic values (timestamps, derived strings), construct the complete expected value using the same logic, then assert ==. Do not assert partial membership of the dynamic value.

For mock assertions: assert EVERY call with ALL args, verify call count. mock.ANY is BANNED -- construct the expected argument dynamically if needed.

Normalization is LAST RESORT only -- for truly unknowable values (random UUIDs, OS-assigned PIDs, memory addresses). Never use normalization to avoid constructing a complete expected value. </CRITICAL>

Tests must validate CONTENT, not just EXISTENCE. Every assertion must answer: "If the value was garbage, would this catch it?"

Reference: Read patterns/assertion-quality-standard.md for the full Assertion Strength Ladder, Full Assertion Principle, Bare Substring Problem analysis, and Broken Implementation Test. Every assertion must be Level 4+ on the ladder.

Rules
RuleBANNED PatternCORRECT Pattern
No existence-only assertionsassert len(result) > 0 (BANNED Level 1)assert result == [expected_item_1, expected_item_2]
No count-only assertionsassert len(result) == 3 (BANNED Level 2)assert result == [item_1, item_2, item_3]
No none-checks without contentassert response is not None (BANNED Level 1)assert response == expected_response
No file existence-only checksassert output_file.exists() (BANNED Level 1)assert output_file.read_text() == "expected content"
No `mock.ANY` everassert_called_with(mock.ANY, mock.ANY) (BANNED -- proves nothing)assert_called_with("expected_arg", expected_obj) (construct dynamically if needed)
Assert every mock call, all argsmock_fn.assert_called() or mock_fn.assert_called_once() (no argument check)mock_fn.assert_has_calls([call(arg1, arg2), ...]) + verify call_count
No partial checks on any outputassert "key" in result (BANNED Level 2)assert result == {"key": "expected_value", ...} (construct dynamically for dynamic output)
Every field of every objectassert result.status == "ok" (BANNED Level 3 without justification)assert result == ExpectedObject(status="ok", data=..., meta=...)
No bare substring on string outputassert "data" in output (BANNED Level 2)assert output == expected (exact equality)
No multiple partials as substituteassert "foo" in r and "bar" in r (BANNED: still partial)assert r == expected_complete_string
No tautological assertionsassert result == func(same_input) (BANNED: tests nothing)Compute expected value independently
Pychoir Matchers

Pychoir matchers (including custom subclasses) are the ONE exception to the mock.ANY ban. Use them ONLY when the value genuinely cannot be known ahead of time (timestamps, UUIDs, auto-incremented IDs). Each use requires a stated justification in a comment.

python
# GOOD: UUID genuinely unknowable, justification stated
from pychoir import IsInstance
assert result == {"id": IsInstance(str), "name": "expected_name"} # id is server-generated UUID
# BAD: Using matcher to avoid computing expected value
assert result == {"count": IsInstance(int), "items": IsInstance(list)} # Lazy - compute the expected values
ESCAPE Analysis (Mandatory Per Test Function)

Before marking ANY test function complete, fill in this template:

ESCAPE: [test_function_name]
CLAIM: What does this test claim to verify?
PATH: What code actually executes?
CHECK: What do the assertions verify?
MUTATION: For each assertion, name the specific production code mutation it catches.
ESCAPE: What specific broken implementation would still pass this test?
IMPACT: What breaks in production if that broken implementation ships?

The MUTATION field is a forcing function: for each assertion in the test, you must name a specific, plausible production code change that would cause that assertion to fail. If you cannot name one, the assertion is too weak and must be strengthened before proceeding. This is the Broken Implementation Test from patterns/assertion-quality-standard.md.

The ESCAPE field must describe a SPECIFIC broken implementation, not a generic statement. "Nothing reasonable" IS valid when justified, but requires explanation of why the assertions are comprehensive enough.

Red flags in ESCAPE analysis:

  • ESCAPE field says "none" or "nothing" without justification
  • ESCAPE field describes something the test DOES catch (means you didn't think hard enough)
  • ESCAPE field is copy-pasted between tests (each test has unique escape paths)
Test Strength Verification (mechanical pre-commit grep)

ESCAPE Analysis is the rigorous version. This is the cheap mechanical version that catches the most common green-mirage patterns at commit time. Run BEFORE any per-task commit:

bash
# 1. Banned substring assertions on serialized output
rg -n 'expect.*stringContaining.*JSON|expect.*stringContaining.*\{' <test_files>
# Replace with: JSON.parse(...) + exact deep equality (toEqual)

This is the start of the file. Read the full SKILL.md on GitHub.

Security

  • Security scanPassed, 95 of 100Pattern checks on the skill's files.
  • Model reviewPassed

Quality evaluation

  • Task evaluationNot runNo evaluation yet. Run one in Skill Studio.

Source

Popularity

Repository stars
10
Repository forks
6
7-day trend score
12

Stars and forks are for the whole GitHub repository, not this skill alone. Not refreshed yet.

Extension points

  • hookPre/post lifecycle hooks

Works with

Any agent vskill installs to: 56 targets in all. These 39 have a page on this site.

  • Claude Code
  • Cursor
  • GitHub Copilot
  • Windsurf
  • Codex
  • Gemini CLI
  • Cline
  • Amp
  • Roo Code
  • Goose
  • Continue
  • Kilo Code
  • Junie
  • Trae
  • OpenHands
  • Qwen Code
  • AI Agent
  • Tabnine Chat
  • Sourcegraph Cody
  • Amazon Q
  • Firebase Genkit
  • Sweep
  • Devin
  • Phind
  • Mentat
  • Claude Desktop
  • Aider
  • GPT Pilot
  • Plandex
  • bolt.new
  • v0
  • Replit Agent
  • Anse
  • TypingMind
  • BetterChatGPT
  • LibreChat
  • Warp AI
  • Pieces
  • Fig AI
Embed badge
vskill VERIFIED badge
[![vskill VERIFIED](https://verified-skill.com/api/v1/skills/axiomantic/spellbook/test-driven-development/badge)](https://verified-skill.com/skills/axiomantic/spellbook/test-driven-development)

Something wrong with this skill or its page? Tell us.