Skip to content
←INDEX / 提示詞庫
TUTORIAL/Claude Code/進階

Claude Code TDD 閉環:先寫會失敗的測試,再寫剛好通過的程式,最後重構

強制 Claude Code 走嚴格的 紅→綠→重構 循環:每個行為先寫一個會失敗的測試(紅),跑給你看它真的失敗,再寫剛好讓它通過的最小實作(綠),最後在測試保護下重構。治 AI『直接寫 happy path、跳過邊界、測試造假』的老毛病。

SakuyaPromptCraft 主筆 · 寫於 2026-06-08
AI 教學 / 腳本Claude Code進階預期輸出說明≈ 610 tokens · 實際用量依工具與輸入而異
Last reviewed2026-06-08Read~11 MIN

01PROMPT

We are building this feature using strict Test-Driven Development. Follow the Red-Green-Refactor cycle and do NOT skip steps. The discipline is non-negotiable: no production code gets written before there is a failing test that demands it.

FEATURE / BEHAVIOR TO BUILD:
{{FEATURE}}

TEST FRAMEWORK & COMMAND:
- Framework / runner: {{TEST_FRAMEWORK}}
- Command to run tests: {{TEST_COMMAND}}

Process for EACH behavior (work one behavior at a time, smallest first):

=== RED ===
1. Write exactly ONE focused test for the next small behavior, including the relevant edge cases for that behavior (empty input, boundary values, error paths) where they belong. Do not write the implementation yet.
2. Run `{{TEST_COMMAND}}` and SHOW me the actual output. The new test MUST fail, and it must fail for the RIGHT reason (asserting the missing behavior — not failing due to an import error, typo, or syntax mistake). If it fails for the wrong reason, fix the test and re-run before continuing.
3. State in one line: what behavior this test pins down.

=== GREEN ===
4. Write the MINIMUM production code needed to make that test pass. No extra features, no speculative abstraction, no handling of cases no test covers yet.
5. Run `{{TEST_COMMAND}}` again and SHOW the output. The target test must now pass AND every previously passing test must still pass. If anything else broke, fix it before moving on.

=== REFACTOR ===
6. With the tests green, look for cleanup: duplication, unclear names, dead code, awkward structure. Refactor WITHOUT changing behavior. Run `{{TEST_COMMAND}}` once more and SHOW output to prove everything is still green. If there is nothing worth refactoring, say so explicitly and move on.

Then repeat the cycle for the next behavior.

Hard rules:
- Never write production code in the same step as writing a test.
- Never edit a test just to make a failing implementation pass — if a test is genuinely wrong, say WHY out loud first, then fix the test, then re-run RED.
- Do not stub out tests to always pass, and do not delete assertions to get green. That is cheating and counts as failure.
- Always paste the REAL test runner output, never a summary like 'tests pass'. If a command cannot be run here, say so explicitly instead of pretending.
- Stop after every full cycle and give me a one-line status: which behavior is now done and what the next behavior will be.

Start with RED for the smallest meaningful behavior.

把方括號 [ ] 內的變數換成你的內容,丟進 Claude Code。

◆ 直接開到工具Claude(記得貼)
RUN站內試跑 / TRY IT
▶ 站內試跑

不用離開網站,直接看這組 prompt 跑出來長怎樣(AI 即時生成,扣 1 點)。

SKILL安裝成 SKILL / INSTALL
安裝成 SKILLClaude Code Agent Skill

不只複製貼上 — 下載後放到 ~/.claude/skills/tdd-red-green-refactor-loop/SKILL.md,之後每個 session 自動可用(觸發時自動載入)。

macOS / Linux
mkdir -p ~/.claude/skills/tdd-red-green-refactor-loop && mv ~/Downloads/SKILL.md ~/.claude/skills/tdd-red-green-refactor-loop/SKILL.md
Windows PowerShell
New-Item -ItemType Directory -Force "$env:USERPROFILE\.claude\skills\tdd-red-green-refactor-loop" | Out-Null; Move-Item "$env:USERPROFILE\Downloads\SKILL.md" "$env:USERPROFILE\.claude\skills\tdd-red-green-refactor-loop\SKILL.md"

02CONTEXT / 使用情境

何時用:寫新函式/類別/模組,且你想要真正可信賴的測試覆蓋、不想事後補一堆假測試時。Bug 修復也適用(先寫重現 bug 的失敗測試)。 為何有效:TDD 是 Anthropic 官方推薦的 Claude Code 工作流之一。Claude Code 有個結構性弱點——預設 implementation-first、只寫 happy path、忽略邊界;在同一個 context 裡硬推 TDD 時,實作邏輯會『滲入』測試(context pollution)。這個提示詞用三個明確關卡(先看測試失敗、寫最小實作、重構後再驗證)+『貼真實 runner 輸出』『不准改測試遷就實作』的硬規則把紀律外顯化,讓 TDD 變成預設行為而非靠意志力。 技巧:① 一定要填對 {{TEST_COMMAND}},AI 才有東西可跑、可貼輸出。② 最關鍵的一步是 RED 階段『確認測試是因為正確理由而失敗』——很多 AI 的假 TDD 其實是 import 寫錯導致的失敗,並非真的在驗行為。③ 想更強制可搭配 Claude Code 的 Hooks(PreToolUse),在沒有對應失敗測試時擋下對實作檔的寫入,但那需要另外設定,本提示詞不依賴它。④ 一次只做一個行為,別貪快叫它一口氣寫十個測試。

03SAMPLE / 期待成果

=== RED === Wrote 1 test: `slugify('') returns ''` (empty input edge case). Ran `npm test`: FAIL src/slugify.test.ts ✕ slugify('') returns '' (2 ms) ReferenceError: slugify is not defined That is the RIGHT kind of failure (function doesn't exist yet). Behavior pinned: empty string in → empty string out. === GREEN === Added minimal `export function slugify(s: string){ return s.trim().toLowerCase().replace(/\s+/g,'-'); }` Ran `npm test`: PASS src/slugify.test.ts (1 passing) === REFACTOR === Nothing meaningful to refactor at this size — moving on. Status: done = empty-input handling. Next behavior = collapse multiple spaces into one dash.

這是預期成果的文字說明。請查看本文實測說明,並以自己的輸入素材小規模試用。

04VARIABLES / 變數說明

01[FEATURE]

要實作的功能或行為描述;可列出你想到的邊界/錯誤情境讓 AI 涵蓋

02[TEST_FRAMEWORK]

測試框架/執行器,例如 Vitest、Jest、pytest、Go test、JUnit

03[TEST_COMMAND]

實際跑測試的指令,例如 npm test、pytest -q、go test ./...,AI 會用它跑並貼輸出

05RESOLVER · 變數代入器0 / 3

填下面的欄位,上方 prompt 會即時替換 [方括號] 內容。填好後按「複製組好的 prompt」直接丟進工具。

修飾
Assembled · 填剩餘變數…
We are building this feature using strict Test-Driven Development. Follow the Red-Green-Refactor cycle and do NOT skip steps. The discipline is non-negotiable: no production code gets written before there is a failing test that demands it.

FEATURE / BEHAVIOR TO BUILD:
{{FEATURE}}

TEST FRAMEWORK & COMMAND:
- Framework / runner: {{TEST_FRAMEWORK}}
- Command to run tests: {{TEST_COMMAND}}

Process for EACH behavior (work one behavior at a time, smallest first):

=== RED ===
1. Write exactly ONE focused test for the next small behavior, including the relevant edge cases for that behavior (empty input, boundary values, error paths) where they belong. Do not write the implementation yet.
2. Run `{{TEST_COMMAND}}` and SHOW me the actual output. The new test MUST fail, and it must fail for the RIGHT reason (asserting the missing behavior — not failing due to an import error, typo, or syntax mistake). If it fails for the wrong reason, fix the test and re-run before continuing.
3. State in one line: what behavior this test pins down.

=== GREEN ===
4. Write the MINIMUM production code needed to make that test pass. No extra features, no speculative abstraction, no handling of cases no test covers yet.
5. Run `{{TEST_COMMAND}}` again and SHOW the output. The target test must now pass AND every previously passing test must still pass. If anything else broke, fix it before moving on.

=== REFACTOR ===
6. With the tests green, look for cleanup: duplication, unclear names, dead code, awkward structure. Refactor WITHOUT changing behavior. Run `{{TEST_COMMAND}}` once more and SHOW output to prove everything is still green. If there is nothing worth refactoring, say so explicitly and move on.

Then repeat the cycle for the next behavior.

Hard rules:
- Never write production code in the same step as writing a test.
- Never edit a test just to make a failing implementation pass — if a test is genuinely wrong, say WHY out loud first, then fix the test, then re-run RED.
- Do not stub out tests to always pass, and do not delete assertions to get green. That is cheating and counts as failure.
- Always paste the REAL test runner output, never a summary like 'tests pass'. If a command cannot be run here, say so explicitly instead of pretending.
- Stop after every full cycle and give me a one-line status: which behavior is now done and what the next behavior will be.

Start with RED for the smallest meaningful behavior.
FAQ · 常見問題

「Claude Code TDD 閉環:先寫會失敗的測試,再寫剛好通過的程式,最後重構」這組提示詞要怎麼用?

這組 prompt 專為 Claude Code 設計。把 prompt 內 3 個方括號 [變數] 換成你自己的內容,貼進 Claude Code 執行即可。難度中等,照變數說明填好後即可上手。

「Claude Code TDD 閉環:先寫會失敗的測試,再寫剛好通過的程式,最後重構」是免費的嗎?

完整 prompt 免費開放閱讀,不用註冊;可保存瀏覽器收藏,登入後可一鍵複製與留言。

用 Claude Code 依這組 prompt 生成的成果可以商用嗎?

prompt 文字本身你可自由使用與修改。但 AI 生成物(圖/音樂/影片/文字)的商用授權,取決於你在 Claude Code 使用的方案與其官方服務條款,請以該工具的授權規範為準。

RELATED你可能也需要

PRO01
TUTORIALSuno v5.5FEATURED
r/SunoAI (anonymous studio engineer)2026-06-12

Suno 工程師思維:4 步驟做出不像 AI 的歌

5.0(1)

Studio engineer 視角拆解 Suno 致命弱點(油炸 vocals、高頻 artifact)+ 4 步驟 DAW workflow + Suno Studio 修音 prompt

高階
Read

免費02
TUTORIALClaude 4.5 SonnetFEATURED
r/ClaudeAI2026-05-14

5 個 6 月 stuck 下來的 Claude 每週 workflow

提案產生器 / 會議處理器 / 內容再利用 / 週五回顧 / 收工 reset — 試了 40 個只有這 5 個沒被丟掉、各省 30+ 分鐘 / 次。

進階
Read

PRO03
TUTORIALClaude 4.5 SonnetFEATURED
r/PromptEngineering2026-05-14

7 個跨 model A/B 測過的 prompt 技巧(不是 vibes)

六個月在 Claude / GPT-4 / Gemini 上用人工 rater A/B 測 200+ prompt 後寫的。包含 persona+constraint stacking / anti-example / role reversal QA / cognitive scaffold / emotional priming / uncertainty CoT / steelman first。

高階
Read

免費04
TUTORIALChatGPTFEATURED
r/ChatGPTPromptGenius2026-05-14

5 個信任檢查單行 prompt(沒有 role-play)

一年的 role-play system prompt + 14-step framework 後總結:真正改變品質的是 5 個單行 prompt。沒有 role、沒有 markdown、沒有「you are an expert」。

入門
Read

免費 · 全文開放閱讀

完整 prompt 已經開放.

免登入閱讀全文、保存瀏覽器收藏;登入後可一鍵複製與留言討論。不用信用卡。

不想註冊?

留個 email,下次有新 prompt 會寄一封簡短摘要給你。退訂一鍵、不轉賣。

每週一期,新上架提示詞 + 模型測試心得。每封信底部都有一鍵取消訂閱。

或訂 RSS feed(30 秒一次的人味選擇)

COMMENTS · 討論區0 則
登入 後可留言。還沒帳號?註冊
目前沒有留言。第一個說說你的經驗。
EMBED · 嵌入 blog / Note一行 iframe HTML、貼進文章即顯示此 prompt 卡片+

適合:部落格、Medium、Notion 公開頁、Substack — 任何支援 iframe / HTML 嵌入的地方。對方點「看完整」會回到本站、是 prompt 庫的免費 backlink。

<iframe src="https://prompt.luvai.net/embed/claude-code-tdd-red-green-refactor-loop" width="100%" height="380" frameborder="0" style="border:1px solid #e0dcd0;border-radius:4px;" loading="lazy" title="PromptCraft Embed"></iframe>
預覽 embed →380px tall · responsive width
發現這個 prompt 過時 / 跑不動 / 有錯字? 回報給我們 →