TDD (Test-Driven Development)
Intent
Use this skill when implementing or changing behavior where correctness, safety, or long-term maintainability are important.
The goal is to drive design and implementation from tests first, using a red–green–refactor loop.
Core Principles
Behavior first
- Start from externally visible behavior or API contracts.
- Tests describe “what” the system should do, not internal details.
Interfaces for testability
- Prefer clear, narrow interfaces over exposing internals just to make testing easier.
- Group related behavior into deeper modules with thin public surfaces.
Strict red–green–refactor loop
- Red: write a failing test that expresses the next behavior.
- Green: write the simplest implementation that makes the test pass.
- Refactor: improve design with tests staying green.
Workflow
Clarify the behavior
- Restate the change in terms of observable behavior (inputs, outputs, side effects).
- Confirm with the user if anything is ambiguous or underspecified.
Locate test boundaries
- Explore the codebase to find existing test patterns and natural seams (modules, services, handlers).
- Choose the highest level that gives good feedback without being brittle (often a service or use-case layer, not individual helpers).
Design or refine interfaces
- Sketch the function, method, or module interface(s) needed.
- Ensure they are testable: deterministic inputs/outputs, minimized global state, clear dependencies (passed in, not hidden).
Write the first test (Red)
- Add or modify a test that:
- Fails for the right reason initially.
- Uses realistic data and names.
- Captures one concrete behavior (happy path or key edge case).
- Add or modify a test that:
Implement just enough code (Green)
- Modify production code minimally to make the new test pass.
- Avoid over-generalizing or implementing future features.
Refactor
- With tests green, look for:
- Duplication across tests or code
- Overly complex functions or conditionals
- Poorly named or misplaced modules
- Refactor in small steps, keeping tests passing after each.
- With tests green, look for:
Repeat
- Add the next most important test:
- New scenario, edge case, or failure mode.
- Continue the red–green–refactor loop until the behavior is well covered and design feels stable.
- Add the next most important test:
Style Guidelines
- Prefer fewer, higher-value tests that capture behavior over many mechanical tests of tiny details.
- Use realistic naming and examples to keep tests readable.
- Use mocks or fakes sparingly; when you mock heavily, consider whether the module boundaries are in the right place.
- When refactoring, be explicit about which changes are purely structural vs. behavioral.