test-driven-development · mikeyobrien — скилл для Claude Code: TDD-цикл по шагам
Скилл ведёт агента по циклу RED → GREEN → REFACTOR и заставляет писать тесты раньше кода. Пригодится, когда нужно разложить спеку или задачу на проверяемые тесты.
npx skills add mikeyobrien/ralph-orchestrator --skill test-driven-development -a claude-codeЧто делает test-driven-development
Скилл принимает вход в трёх режимах. Если указан файл .spec.md с критериями Given/When/Then, он разбирает спеку и генерирует по одному тесту-заглушке на каждый критерий — с телом todo!(). Если на входе .code-task.md или просто описание задачи, агент сначала находит в репозитории существующие тестовые паттерны, а потом пишет падающие тесты под требования.
Дальше всё идёт по одному циклу: RED — тесты падают по правильной причине, GREEN — минимальная реализация без лишнего, REFACTOR — чистка с прогоном тестов после каждой правки. Перед написанием тестов скилл советует посмотреть 2-3 соседних тестовых файла и повторить их структуру, хелперы и стиль ассертов.
Для property-тестов есть отдельный блок про proptest: применять только к чистым функциям с детерминированным выводом и нетривиальным пространством входов. Новую зависимость proptest скилл не советует тянуть без веской причины. В события завершения встраивается доказательство покрытия — например, ralph emit "build.done" "tests: pass, lint: pass, typecheck: pass, audit: pass, coverage: pass (82%)". Если покрытие снять не удалось, нужно объяснить почему и приложить точечные тесты.
Какие задачи решает
- разложить спеку с Given/When/Then на отдельные тесты
- получить падающие тесты до того, как написан код
- повторить тестовые паттерны конкретного крейта, а не тащить чужие
- решить, нужен ли здесь property-тест или хватит примера
- приложить доказательство покрытия к событию завершения
Примеры запросов агенту
- разбери
.spec.mdи сгенерируй тесты-заглушки по каждому критерию - напиши падающие тесты под эту задачу, потом минимальную реализацию
- проверь, стоит ли здесь
proptest, и обоснуй
Как установить test-driven-development
1Через Skills CLI (Vercel)
npx skills add mikeyobrien/ralph-orchestrator --skill test-driven-development -a claude-code2Вручную: положить файлы
~/.claude/skills/test-driven-development/SKILL.mdПапка скилла целиком; для одного проекта — .claude/skills/test-driven-development/
1Через Skills CLI (Vercel)
npx skills add mikeyobrien/ralph-orchestrator --skill test-driven-development -a codex2Вручную: положить файлы
.agents/skills/test-driven-development/SKILL.mdДля всех проектов — ~/.agents/skills/
1Через Skills CLI (Vercel)
npx skills add mikeyobrien/ralph-orchestrator --skill test-driven-development -a cursor2Вручную: положить файлы
.cursor/skills/test-driven-development/SKILL.mdCursor читает и .agents/skills/, и .claude/skills/
1GitHub CLI
gh skill install mikeyobrien/ralph-orchestrator test-driven-development2Вручную: положить файлы
.github/skills/test-driven-development/SKILL.md1Через Skills CLI (Vercel)
npx skills add mikeyobrien/ralph-orchestrator --skill test-driven-development -a gemini-cli2Командой платформы
gemini skills install https://github.com/mikeyobrien/ralph-orchestrator --path .claude/skills/test-driven-developmentВручную: положить файлы
.devin/skills/test-driven-development/SKILL.mdСтарый путь .windsurf/skills/ тоже читается
Через Skills CLI (Vercel)
npx skills add mikeyobrien/ralph-orchestrator --skill test-driven-development -a opencodeClaude.ai
Упакуйте папку в zip и загрузите в Settings → Capabilities → Skills
По шагам, с командами для каждой платформы: Как установить скилл в Claude Code: пять способов
Из того же набора4
Другие версии test-driven-development
Похожие
Рядом в теме «Тесты и QA»
Всё по теме «Тесты и QA» →Вопросы о test-driven-development
Как установить test-driven-development в Claude?
Выполните npx skills add mikeyobrien/ralph-orchestrator --skill test-driven-development -a claude-code. Скилл окажется в ~/.claude/skills/test-driven-development/SKILL.md.
Что делает test-driven-development?
Ведёт агента по циклу RED → GREEN → REFACTOR: сначала падающие тесты, потом минимальная реализация, потом чистка. Работает от спеки, файла задачи или обычного описания.
Когда скилл советует брать proptest?
Только если функция чистая, вывод детерминирован, а пространство входов или краевые случаи нетривиальны. Без веской причины новую зависимость он добавлять не советует.
Исходный текст
SKILL.md · MIT
---
name: test-driven-development
description: Unified TDD skill with three input modes — from spec, from task, or from description. Enforces test-first development using repository patterns, with proptest guidance and backpressure integration.
type: anthropic-skill
version: "1.0"
metadata:
internal: true
---
# Test-Driven Development
## Overview
One skill for all TDD workflows. Enforces test-first development using existing repository patterns. Three input modes handle different entry points — specs, task files, or ad-hoc descriptions — but the core cycle is always RED → GREEN → REFACTOR.
## Input Modes
Detect the input type and follow the corresponding mode:
### Mode A: From Spec (`.spec.md`)
Use when the input references a `.spec.md` file with Given/When/Then acceptance criteria.
1. **Locate and parse** the spec file — extract all Given/When/Then triples
2. **Generate one test stub per criterion** with `todo!()` bodies:
```rust
/// Spec: <spec-file> — Criterion #<N>
/// Given <given text>
/// When <when text>
/// Then <then text>
#[test]
fn <spec_name>_criterion_<N>_<slug>() {
todo!("Implement: <then text>");
}
```
3. **Verify stubs compile** but fail: `cargo test --no-run -p <crate>`
4. Proceed to the [TDD Cycle](#tdd-cycle) to make stubs pass
**Programmatic support:** `ralph_core::preflight::{extract_acceptance_criteria, extract_criteria_from_file, extract_all_criteria}` can parse criteria from spec files.
### Mode B: From Task (`.code-task.md`)
Use when the input references a `.code-task.md` file or a specific implementation task.
1. **Read the task** and identify acceptance criteria or requirements
2. **Discover patterns** (see [Pattern Discovery](#pattern-discovery))
3. **Design test scenarios** covering normal operation, edge cases, and error conditions
4. **Write failing tests** for all requirements before any implementation
5. Proceed to the [TDD Cycle](#tdd-cycle)
### Mode C: From Description
Use for ad-hoc tasks without a spec or task file.
1. **Clarify requirements** from the description
2. **Discover patterns** (see [Pattern Discovery](#pattern-discovery))
3. **Write failing tests** targeting the described behavior
4. Proceed to the [TDD Cycle](#tdd-cycle)
## Pattern Discovery
Before writing tests, discover existing conventions:
```bash
rg --files -g "crates/*/tests/*.rs"
rg -n "#\[cfg\(test\)\]" crates/
```
Read 2-3 relevant test files near the target code. Mirror:
- Test module layout, naming, and assertion style
- Fixture helpers and test utilities
- Use of `tempfile`, scenarios, or harnesses
## TDD Cycle
### 1) RED — Failing Tests
- Write tests for the exact behavior required
- Run tests to confirm failure **for the right reason**
- If tests pass without implementation, the test is wrong
### 2) GREEN — Minimal Implementation
- Write the minimum code to make tests pass
- No extra features or refactoring during this step
### 3) REFACTOR — Clean Up
- Improve implementation and tests while keeping tests green
- Align with surrounding codebase conventions
- Re-run tests after every change
## Proptest Guidance
Use `proptest` only when ALL of:
- Function is pure (no I/O, no time, no globals)
- Deterministic output for given input
- Non-trivial input space or edge cases
```rust
proptest! {
#[test]
fn round_trip(input in "[a-z0-9]{0,32}") {
let encoded = encode(input.as_str());
let decoded = decode(&encoded).expect("should decode");
prop_assert_eq!(decoded, input);
}
}
```
Don't introduce proptest as a new dependency without strong justification.
## Backpressure Integration
Include coverage evidence in completion events:
```bash
ralph emit "build.done" "tests: pass, lint: pass, typecheck: pass, audit: pass, coverage: pass (82%)"
```
Run `cargo tarpaulin --out Html --output-dir coverage --skip-clean` when feasible. If coverage cannot be run, state why and include targeted test evidence instead.
## Test Location Rules
- Spec maps to a single module → inline `#[cfg(test)]` tests
- Spec spans multiple modules → integration test in `crates/<crate>/tests/`
- CLI behavior → `crates/ralph-cli/tests/`
- Follow existing patterns in the target crate
## Anti-Patterns
- Writing implementation before tests
- Generating tests that pass without implementation
- Copying tests from other crates without adapting to local patterns
- Adding proptest when a simple example test suffices
- Emitting completion events without coverage evidence
© mikeyobrien · MIT · mikeyobrien/ralph-orchestrator