ワンクリックで
test-driven-development
Use when implementing any feature or bugfix, before writing implementation code
Codex または Claude でインストール この Prompt をコピーして Codex、Claude、または他のアシスタントに貼り付けると、Skill ページを確認してインストールできます。
メニュー
Use when implementing any feature or bugfix, before writing implementation code
Codex または Claude でインストール この Prompt をコピーして Codex、Claude、または他のアシスタントに貼り付けると、Skill ページを確認してインストールできます。
SOC 職業分類に基づく
| name | test-driven-development |
| description | Use when implementing any feature or bugfix, before writing implementation code |
| source | https://github.com/Ethanon/developer.ai |
| license | MIT |
Write the test first. Watch it fail. Write minimal code to pass.
Core principle: If you didn't watch the test fail, you don't know if it tests the right thing.
Violating the letter of the rules is violating the spirit of the rules.
Always:
Exceptions (ask the project owner):
Thinking "skip TDD just this once"? Stop. That's rationalization.
NO PRODUCTION CODE WITHOUT A FAILING TEST FIRST
Write code before the test? Delete it. Start over.
No exceptions:
Implement fresh from tests. Period.
Write one minimal test showing what should happen.
Good:
def test_retries_failed_operations_three_times() -> None:
attempts = 0
def operation() -> str:
nonlocal attempts
attempts += 1
if attempts < 3:
raise RuntimeError('fail')
return 'success'
result = retry_operation(operation)
assert result == 'success'
assert attempts == 3
Clear name, tests real behavior, one thing.
Bad:
def test_retry_works() -> None:
mock_op = MagicMock(side_effect=[RuntimeError(), RuntimeError(), 'success'])
retry_operation(mock_op)
assert mock_op.call_count == 3
Vague name, tests mock not code.
Requirements:
test_<behavior>, not test_<function>)MANDATORY. Never skip.
pytest tests/test_module.py::test_retries_failed_operations_three_times -v
Confirm:
Test passes? You're testing existing behavior. Fix test.
Test errors? Fix error, re-run until it fails correctly.
Write simplest code to pass the test.
Good:
from typing import Callable, TypeVar
T = TypeVar('T')
def retry_operation(fn: Callable[[], T], max_attempts: int = 3) -> T:
for attempt in range(max_attempts):
try:
return fn()
except Exception:
if attempt == max_attempts - 1:
raise
raise RuntimeError('unreachable')
Just enough to pass.
Bad:
def retry_operation(
fn: Callable[[], T],
max_attempts: int = 3,
backoff: Literal['linear', 'exponential'] = 'linear',
on_retry: Callable[[int], None] | None = None,
exceptions: tuple[type[Exception], ...] = (Exception,),
) -> T:
# YAGNI
...
Over-engineered.
Don't add features, refactor other code, or "improve" beyond the test.
MANDATORY.
pytest tests/test_module.py -v
Confirm:
Test fails? Fix code, not test.
Other tests fail? Fix now.
After green only:
Keep tests green. Don't add behavior.
Next failing test for next feature.
| Quality | Good | Bad |
|---|---|---|
| Minimal | One thing. "and" in name? Split it. | test_validates_email_and_domain_and_whitespace |
| Clear | Name describes behavior | test1, test_foo |
| Shows intent | Demonstrates desired API | Obscures what code should do |
Fixtures over setup/teardown:
# GOOD
@pytest.fixture
def user_repo(tmp_path: Path) -> UserRepository:
return UserRepository(db_path=tmp_path / 'test.db')
def test_saves_user(user_repo: UserRepository) -> None:
user = User(name='Alice', email='alice@example.com')
user_repo.save(user)
assert user_repo.find_by_email('alice@example.com') == user
Parametrize for multiple cases:
@pytest.mark.parametrize('email', ['', 'notanemail', '@nodomain'])
def test_rejects_invalid_email(email: str) -> None:
result = validate_email(email)
assert result.is_err()
Fake time, don't sleep:
def test_expires_after_ttl(freezer: FrozenDateTimeFactory) -> None:
cache = Cache(ttl_seconds=60)
cache.set('key', 'value')
freezer.tick(61)
assert cache.get('key') is None
Use freezegun / time-machine; never time.sleep() in tests.
"I'll write tests after to verify it works"
Tests written after code pass immediately. Passing immediately proves nothing.
"I already manually tested all the edge cases"
Manual testing is ad-hoc. No record, can't re-run, easy to forget under pressure.
"Deleting X hours of work is wasteful"
Sunk cost fallacy. Keeping code you can't trust is the real waste.
"Tests after achieve the same goals"
Tests-after answer "What does this do?" Tests-first answer "What should this do?" Tests-after are biased by your implementation.
| Excuse | Reality |
|---|---|
| "Too simple to test" | Simple code breaks. Test takes 30 seconds. |
| "I'll test after" | Tests passing immediately prove nothing. |
| "Tests after achieve same goals" | Tests-after = "what does this do?" Tests-first = "what should this do?" |
| "Already manually tested" | Ad-hoc is not systematic. No record, can't re-run. |
| "Deleting X hours is wasteful" | Sunk cost fallacy. Keeping unverified code is technical debt. |
| "Keep as reference, write tests first" | You'll adapt it. That's testing after. Delete means delete. |
| "Need to explore first" | Fine. Throw away exploration, start with TDD. |
| "Test hard = design unclear" | Listen to test. Hard to test = hard to use. |
| "TDD will slow me down" | TDD faster than debugging. Pragmatic = test-first. |
All of these mean: Delete code. Start over with TDD.
Bug: Empty email accepted
RED
def test_rejects_empty_email() -> None:
result = submit_form({'email': ''})
assert result['error'] == 'Email required'
Verify RED
$ pytest tests/test_form.py::test_rejects_empty_email -v
FAILED: AssertionError: assert None == 'Email required'
GREEN
def submit_form(data: dict[str, str]) -> dict[str, str | None]:
if not data.get('email', '').strip():
return {'error': 'Email required'}
...
Verify GREEN
$ pytest tests/test_form.py -v
PASSED
REFACTOR Extract validation for multiple fields if needed.
Before marking work complete:
pytest)mypy/pyright)Can't check all boxes? You skipped TDD. Start over.
| Problem | Solution |
|---|---|
| Don't know how to test | Write wished-for API. Write assertion first. Ask the project owner. |
| Test too complicated | Design too complicated. Simplify interface. |
| Must mock everything | Code too coupled. Use dependency injection or pass a Protocol. |
| Test setup huge | Extract fixtures. Still complex? Simplify design. |
Bug found? Write failing test reproducing it. Follow TDD cycle. Test proves fix and prevents regression.
Never fix bugs without a test.
When adding mocks or test utilities, read testing-anti-patterns.md to avoid common pitfalls:
Production code -> test exists and failed first
Otherwise -> not TDD
No exceptions without the project owner's explicit approval.
Reference for using a "DevHarness" escape hatch to render auth-gated frontend screens against `vite preview` (or your project's local preview equivalent) without booting the full backend. Lets you iterate on mobile-viewport UI polish with a screenshot-driven loop.
Code refactoring patterns and techniques for improving code quality without changing behavior. Use for cleaning up legacy code, reducing complexity, or improving maintainability.
Use when receiving code review feedback, before implementing suggestions, especially if feedback seems unclear or technically questionable - requires technical rigor and verification, not performative agreement or blind implementation
Reference for what visual smoke covers (and doesn't) when a fix touches client-side UI or styles. The actual smoke runs automatically in CI; this skill documents the manual decision tree for routes CI can't reach (authenticated screens, multi-step flows, post-auth overlays).
Code refactoring patterns and techniques for improving code quality without changing behavior. Use for cleaning up legacy code, reducing complexity, or improving maintainability.
Use when receiving code review feedback, before implementing suggestions, especially if feedback seems unclear or technically questionable - requires technical rigor and verification, not performative agreement or blind implementation