一键导入
codex-test-driven-development
Use before feature, bugfix, or refactor implementation when behavior can be tested; enforces Red-Green-Refactor discipline.
用 Codex 或 Claude 帮你安装 复制这段 Prompt,粘贴到 Codex、Claude 或其他助手里,让它检查 Skill 页面并帮你完成安装。
菜单
Use before feature, bugfix, or refactor implementation when behavior can be tested; enforces Red-Green-Refactor discipline.
用 Codex 或 Claude 帮你安装 复制这段 Prompt,粘贴到 Codex、Claude 或其他助手里,让它检查 Skill 页面并帮你完成安装。
基于 SOC 职业分类
Use for project memory, decisions, handoffs, genome, knowledge index, changelog, and patterns that must persist across sessions.
Use for frontend, backend, mobile, debugging, security, or specialized engineering work that needs focused domain references and strict boundaries.
Use for prototype, MVP, fullstack feature, from-scratch feature, or multi-domain work that needs a SPEC.md before planning or implementation. Do not use for tiny one-file edits.
Use when code changes may require documentation updates; maps git diff to candidate docs without auto-editing documentation.
Use before completion, PR, deploy, handoff, or when verifying code changes. Runs advisory or blocking checks and reports evidence.
Use when the task involves reading, creating, or editing `.docx` documents, especially when formatting or layout fidelity matters; prefer `python-docx` plus the bundled `scripts/render_docx.py` for visual checks.
| name | codex-test-driven-development |
| description | Use before feature, bugfix, or refactor implementation when behavior can be tested; enforces Red-Green-Refactor discipline. |
| load_priority | on-demand |
Write test first → watch it fail → write minimal code to pass → watch it pass → refactor. Delete code written before tests. No exceptions. Integrate with $gate for automated verification. Use $tdd or $red-green to activate.
$codex-test-driven-development, $tdd, or $red-green.codex-workflow-autopilot routes to build or fix workflow.codex-intent-context-analyzer detects implementation intent.NO PRODUCTION CODE WITHOUT A FAILING TEST FIRST
Write code before the test? Delete it. Start over.
No exceptions:
Implement fresh from tests. Period.
Violating the letter of the rules is violating the spirit of the rules.
Always:
Exceptions (ask the human):
Thinking "skip TDD just this once"? Stop. That's rationalization.
Task type → Implementation needed?
|- Yes → Write failing test (RED)
| |- Verify it fails correctly
| |- Write minimal code (GREEN)
| |- Verify it passes + all tests pass
| |- Refactor (keep green)
| `- Next test → repeat
|
`- No → skip TDD
Write one minimal test showing what should happen.
Good — Python:
def test_retries_failed_operations_three_times():
attempts = 0
def operation():
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.
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);
});
Bad:
test('retry works', async () => {
const mock = jest.fn()
.mockRejectedValueOnce(new Error())
.mockResolvedValueOnce('success');
await retryOperation(mock);
expect(mock).toHaveBeenCalledTimes(2);
});
Vague name, tests mock not code.
Requirements:
MANDATORY. Never skip.
# Python
python -m pytest tests/path/test_module.py::test_name -v
# JavaScript/TypeScript
npm test -- --grep "test name"
# Go
go test -run TestName -v ./...
Confirm:
Test passes immediately? 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:
async def retry_operation(fn, max_retries=3):
for i in range(max_retries):
try:
return fn()
except Exception:
if i == max_retries - 1:
raise
Just enough to pass.
Bad:
async def retry_operation(
fn,
max_retries=3,
backoff="exponential",
on_retry=None,
timeout=30,
jitter=True,
):
# YAGNI — over-engineered
Don't add features, refactor other code, or "improve" beyond the test.
MANDATORY.
# Run specific test
python -m pytest tests/path/test_module.py::test_name -v
# Run ALL tests to check for regressions
python -m pytest tests/ -q
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 | test_1, test_it_works |
| Shows intent | Demonstrates desired API | Obscures what code should do |
| Real code | Tests actual implementation | Tests mock behavior |
"I'll write tests after to verify it works"
Tests written after code pass immediately. Passing immediately proves nothing:
Test-first forces you to see the test fail, proving it actually tests something.
"I already manually tested all the edge cases"
Manual testing is ad-hoc. You think you tested everything but:
Automated tests are systematic. They run the same way every time.
"Deleting X hours of work is wasteful"
Sunk cost fallacy. The time is already gone. Your choice now:
The "waste" is keeping code you can't trust.
"TDD is dogmatic, being pragmatic means adapting"
TDD IS pragmatic:
"Pragmatic" shortcuts = debugging in production = slower.
| 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 ≠ 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. |
| "Manual test faster" | Manual doesn't prove edge cases. You'll re-test every change. |
| "Existing code has no tests" | You're improving it. Add tests for existing code. |
| "This is different because..." | It's not. Start with TDD. |
All of these mean: Delete code. Start over with TDD.
Bug: Empty email accepted
RED
def test_rejects_empty_email():
result = submit_form({"email": ""})
assert result["error"] == "Email required"
Verify RED
$ python -m pytest tests/test_form.py::test_rejects_empty_email -v
FAIL: AssertionError: expected 'Email required', got None
GREEN
def submit_form(data):
if not data.get("email", "").strip():
return {"error": "Email required"}
# ...
Verify GREEN
$ python -m pytest tests/test_form.py -v
PASS (all tests)
REFACTOR Extract validation for multiple fields if needed.
Before marking work complete:
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 human. |
| Test too complicated | Design too complicated. Simplify interface. |
| Must mock everything | Code too coupled. Use dependency injection. |
| Test setup huge | Extract helpers. 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.
After TDD cycle, run quality gate:
# Quick check
python codex-execution-quality-gate/scripts/auto_gate.py --mode quick --project-root <repo>
# Smart test selection for changed files
python codex-execution-quality-gate/scripts/smart_test_selector.py --project-root <repo>
| Workflow Phase | TDD Requirement |
|---|---|
$plan task breakdown | Each task must include test-first steps |
$create implementation | RED-GREEN-REFACTOR per feature unit |
$debug bug fix | Failing reproduction test BEFORE fix attempt |
$review code review | Verify TDD compliance in changeset |
When adding mocks or test utilities, see references/testing-anti-patterns.md to avoid common pitfalls.
references/testing-anti-patterns.md: common testing mistakes and how to avoid them.Production code → test exists and failed first
Otherwise → not TDD
No exceptions without the human's explicit permission.