---
name: Test-Driven Development
description: Write tests first, then code.
---
# Test-Driven Development (TDD)

Write a failing test before any production code. This inverts the usual habit of writing code and bolting on tests, and it forces precise thinking about interface and behavior first.

## The cycle (Red → Green → Refactor)
1. **Red.** Write one small test for the next behavior you want. Run it. It must fail for the right reason (not a syntax error or a missing import). If it fails for the wrong reason, fix the setup first.
2. **Green.** Write the minimum code to make the test pass. Ugly code is acceptable here. Do not add behavior the test does not demand.
3. **Refactor.** With tests green, improve the code: extract duplication, rename, simplify. Run tests after each change. The test net is what makes refactoring safe.

## Rules of thumb
- One assertion concept per test. If a test checks three unrelated things, a failure doesn't tell you which behavior broke.
- Name tests as sentences: `shouldRejectTransferWhenBalanceIsNegative`, not `test1`.
- Test behavior, not implementation. If a refactor forces you to rewrite tests, the tests were coupled to the wrong thing.
- When a bug is reported, first reproduce it as a failing test, then fix. This turns the bug into a permanent regression guard.
- Keep the cycle fast (seconds). Slow tests get skipped, and skipped tests stop protecting you.