Разработка фич со строгим подходом «тесты до кода» — для новых фич, требующих покрытия тестами

Звёзды4 465
Авторnyldn
Установок83

Установка

SKILL.md

Test-Driven Development (TDD)

MANDATORY COMPLIANCE — DO NOT SKIP

When this skill is invoked, you MUST run the TDD pipeline through orchestrate.sh (red → green → refactor) with real provider dispatch. You are PROHIBITED from:

  • Writing implementation before a failing test exists
  • Simulating provider output instead of dispatching via orchestrate.sh
  • Declaring the task "too small for TDD" and skipping the cycle without asking the user
  • Marking work complete while any test is red or skipped
  • Rationalizing that a direct edit is faster — the user invoked TDD for test-first discipline

The Iron Law

<!-- --><HARD-GATE> NO PRODUCTION CODE WITHOUT A FAILING TEST FIRST </HARD-GATE><!-- -->

Violating the letter of this rule is violating the spirit of this rule.

Write code before the test? Delete it. Start over.

  • Don't keep it as "reference"
  • Don't "adapt" it while writing tests
  • Don't look at it
  • Delete means delete

Red-Green-Refactor Cycle

   ┌─────────┐
   │   RED   │ ← Write ONE failing test
   └────┬────┘
        ↓
   ┌─────────┐
   │  VERIFY │ ← Watch it FAIL (mandatory)
   └────┬────┘
        ↓
   ┌─────────┐
   │  GREEN  │ ← Write MINIMAL code to pass
   └────┬────┘
        ↓
   ┌─────────┐
   │  VERIFY │ ← Watch it PASS (mandatory)
   └────┬────┘
        ↓
   ┌─────────┐
   │REFACTOR │ ← Clean up (stay green)
   └────┬────┘
        ↓
     [REPEAT]

Phase 1: RED - Write Failing Test

Write ONE minimal test showing what should happen.

Good Test:

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);
});
  • Clear name describing behavior
  • Tests real code, not mocks
  • One thing only

Bad Test:

test('retry works', async () => {  // Vague name
  const mock = jest.fn()           // Tests mock, not code
    .mockRejectedValueOnce(new Error())
    .mockResolvedValueOnce('success');
  // ...
});

Phase 1.5: Adversarial Test Design Review (RECOMMENDED)

After writing the initial test(s) but BEFORE verifying they fail, challenge the test design with a second provider. A single-model test suite often has systematic blind spots — the same model that writes the tests will write implementation that trivially satisfies them. An adversarial review catches scenarios that would pass with a stub that doesn't actually work.

If an external provider is available, dispatch the test specs for challenge:

review_provider=""
command -v codex >/dev/null 2>&1 && review_provider="codex"
[[ -z "$review_provider" ]] && command -v agy >/dev/null 2>&1 && review_provider="agy"
[[ -z "$review_provider" ]] && command -v gemini >/dev/null 2>&1 && review_provider="gemini"

if [[ -n "$review_provider" ]]; then
  "${HOME}/.claude-octopus/plugin/scripts/orchestrate.sh" spawn "$review_provider" \
    "Review these test specifications for a TDD workflow. Your job is to find gaps, not confirm quality.

1. What SCENARIOS are missing? (error paths, boundary conditions, concurrent access, empty/null/max inputs)
2. What BOUNDARY CONDITIONS are untested? (off-by-one, integer overflow, empty strings, max-length strings)
3. Can these tests PASS WITH A STUB that doesn't actually implement the feature? If yes, what test would catch the stub?
4. Do the tests verify BEHAVIOR or IMPLEMENTATION? (Tests should verify what, not how)

TEST SPECS:
<paste test code here>"
fi

After receiving the challenge:

  • Add any genuinely missing test cases to the RED phase
  • Strengthen any tests that could pass with a trivial stub
  • Dismiss challenges that test implementation details rather than behavior

Skip with --fast or when user requests speed over thoroughness.


Phase 2: VERIFY RED - Watch It Fail

MANDATORY. Never skip.

npm test path/to/test.test.ts

Confirm:

  • Test fails (not errors)
  • Failure message is what you expected
  • Fails because feature is missing (not typos)
OutcomeAction
Test passesYou're testing existing behavior. Fix the test.
Test errorsFix error, re-run until it fails correctly.
Test fails correctlyProceed to GREEN.

Phase 3: GREEN - Minimal Code

Write the simplest code to pass the test. Nothing more.

Good:

async function retryOperation<T>(fn: () => Promise<T>): Promise<T> {
  for (let i = 0; i < 3; i++) {
    try { return await fn(); }
    catch (e) { if (i === 2) throw e; }
  }
  throw new Error('unreachable');
}

Bad (YAGNI violation):

async function retryOperation<T>(
  fn: () => Promise<T>,
  options?: {
    maxRetries?: number;           // Not needed yet
    backoff?: 'linear' | 'expo';   // Not needed yet
    onRetry?: (n: number) => void; // Not needed yet
  }
): Promise<T> { /* ... */ }

Phase 4: VERIFY GREEN - Watch It Pass

MANDATORY.

npm test path/to/test.test.ts

Confirm:

  • Test passes
  • All other tests still pass
  • Output is clean (no errors, warnings)
OutcomeAction
Test failsFix the code, not the test.
Other tests failFix them now.
All passProceed to REFACTOR.

Phase 5: REFACTOR - Clean Up

Only after GREEN:

  • Remove duplication
  • Improve names
  • Extract helpers

Keep tests green throughout. Don't add new behavior.

Common Rationalizations

ExcuseReality
"Too simple to test"Simple code breaks. Test takes 30 seconds.
"I'll test after"Tests passing immediately prove nothing.
"Already manually tested"Ad-hoc ≠ systematic. No record, can't re-run.
"Deleting X hours is wasteful"Sunk cost fallacy. Unverified code is debt.
"Need to explore first"Fine. Throw away exploration, start with TDD.
"TDD will slow me down"TDD is faster than debugging.

Strategy Rotation

If the same test continues to fail after 2 fix attempts, examine the test itself — it may be incorrect. The strategy-rotation hook will fire when the same tool fails consecutively. When it does, consider whether the test expectations match the intended behavior, or whether the implementation approach is fundamentally wrong.


Red Flags - STOP and Start Over

If you catch yourself:

  • Writing code before test
  • Test passes immediately (didn't watch it fail)
  • Rationalizing "just this once"
  • "I already manually tested it"
  • "Keep as reference" or "adapt existing code"
  • "This is different because..."

ALL of these mean: Delete code. Start over with TDD.

Bug Fix Example

Bug: Empty email accepted

RED:

test('rejects empty email', async () => {
  const result = await submitForm({ email: '' });
  expect(result.error).toBe('Email required');
});

VERIFY RED:

$ npm test
FAIL: expected 'Email required', got undefined

GREEN:

function submitForm(data: FormData) {
  if (!data.email?.trim()) {
    return { error: 'Email required' };
  }
  // ...
}

VERIFY GREEN:

$ npm test
PASS

Verification Checklist

Before marking work complete:

  • <!-- -->Every new function/method has a test
  • <!-- -->Watched each test fail before implementing
  • <!-- -->Each test failed for expected reason
  • <!-- -->Wrote minimal code to pass each test
  • <!-- -->All tests pass
  • <!-- -->Output clean (no errors, warnings)

Can't check all boxes? You skipped TDD. Start over.

Integration with Claude Octopus

When using octopus workflows:

WorkflowTDD Integration
probe (research)Research testing patterns for the domain
grasp (define)Define test requirements in spec
tangle (develop)Enforce TDD for each implementation task
ink (deliver)Verify all tests pass before delivery
squeeze (security)Red team tests security controls

When Stuck

ProblemSolution
Don't know how to testWrite the API you wish existed. Assert first.
Test too complicatedDesign too complicated. Simplify interface.
Must mock everythingCode too coupled. Use dependency injection.
Test setup hugeExtract helpers. Still complex? Simplify design.

The Bottom Line

Production code exists → Test exists that failed first
Otherwise → Not TDD

No exceptions without explicit user permission.

Вставить в README

Ссылка на карточку для вашего README — без картинок и счётчиков.

[DarkPlay: skill-tdd](https://darkplay.ru/ai/skills/nyldn-claude-octopus-skill-tdd)

Похожие скиллы и другие разделы каталога

Популярное в разделе «Скиллы»

Самые востребованные скиллов раздела по установкам и звёздам.

find-skillsvercel-labs · Помогает находить и устанавливать навыки агентов по запросам вроде «как сделать X»…
4 400 000 устан.
grill-memattpocock · Настойчивое интервью для доработки плана или дизайна.
1 600 000 устан.
hyperframesheygen-com · Обязательная точка входа для любых задач по видео, анимации и motion-графике в…
1 600 000 устан.
hyperframes-cliheygen-com · Цикл разработки HyperFrames CLI: init, add, render, preview, publish и другие команды.
1 600 000 устан.
agent-browservercel-labs · CLI для автоматизации браузера для ИИ-агентов: навигация по страницам, заполнение форм…
1 600 000 устан.
media-useheygen-com · Agent Media OS: единый навык для медиа в HyperFrames — BGM, SFX, изображения, голос, LUT.
1 500 000 устан.
hyperframes-registryheygen-com · Установка и подключение блоков реестра в композиции HyperFrames через add и catalog.
1 400 000 устан.
grill-with-docsmattpocock · Настойчивое интервью для доработки плана или дизайна, попутно создающее документацию (ADR…
1 300 000 устан.
improve-codebase-architecturemattpocock · Поиск в кодовой базе возможностей для углубления, визуальный HTML-отчёт о них и детальный…
1 300 000 устан.
tddmattpocock · Разработка через тестирование (TDD): red-green-refactor и интеграционные тесты.
1 300 000 устан.
Похожее в других разделах каталога

Соседние разделы каталога: возможно, нужный инструмент живёт там.

mattpocock-skillsmattpocock · Агентские навыки Matt Pocock для настоящей инженерии: разбор задач, потоки спецификаций и…
41 комп.
superpowersobra · Базовая библиотека навыков для Claude Code: TDD, отладка, паттерны совместной работы и…
16 комп.
eccaffaan-m · Нативный для harness операторский слой ECC: 67 агентов, 278 навыков, 94 шима устаревших…
441 комп.
andrej-karpathy-skillsmultica-ai · Правила поведения для снижения типичных ошибок LLM при программировании: думай перед…
1 комп.
Agent Evaluatoraffaan-m · Оценивает результат агента по рубрике качества из 5 критериев (точность, полнота…
225 587 ★
Network Architectaffaan-m · Проектирует корпоративные и распределённые сети с маршрутизацией и автоматизацией.
225 587 ★
Opensource Forkeraffaan-m · Форкает проект для open-source: чистит секреты, ссылки и историю git.
225 587 ★
Opensource Packageraffaan-m · Готовит open-source упаковку: CLAUDE.md, README, LICENSE, CONTRIBUTING и шаблоны.
225 587 ★
Opensource Sanitizeraffaan-m · Проверяет open-source форк на утечки секретов, PII и опасные файлы перед релизом.
225 587 ★
Skill Createaffaan-m · Анализирует локальную историю Git, извлекает паттерны кодирования и генерирует файлы…
225 587 ★

Лучшие ИИ-инструменты для программирования

ИИ для программирования

Подборка нейросетей и ИИ-ассистентов для разработки и автоматизации кода. Сервисы, которые ускоряют написание, ревью и отладку, экономят часы рутины и снижают порог входа в сложные

GenAPIGenapi
По запросу
5.0
Notepad++ AINotepad-plus-plus
По запросу
4.9
GitHub CopilotGitHub
По подписке
4.9
Creatium MaxCremax
По запросу
4.8
Emacs AIGnu
По запросу
4.8
KiteKite
По запросу
4.8
Amazon Q DeveloperAmazon
По запросу
4.8
VECTA
Есть бесплатный тариф
4.8
SoftPractice
Есть бесплатный тариф
4.8
VibeForge
Есть бесплатный тариф
4.7

Лучшие ИИ-инструменты для генерации видео

Генерация видео

Подборка нейросетей для генерации и монтажа видео. Инструменты, которые превращают текст в готовые ролики, экономят часы на съемках и постпродакшне. Подходит для SMM-специалистов,

VEED.IOVeed
По запросу
5.0
MootionMootion
По запросу
5.0
FlyviFlyvi
Есть бесплатный тариф
4.9
Google Veo 3.1Google
Платно
4.9
Sora (OpenAI)OpenAI
Платно
4.9
PikaPika
Платно
4.9
captions space
Есть бесплатный тариф
4.8
Клайп
Есть бесплатный тариф
4.8
viralpulse.appViralpulse
По запросу
4.8
Viral Maker AIViral-maker
Есть бесплатный тариф
4.8

Лучшие ИИ-инструменты для генерации текста и копирайтинга

Генерация текста и копирайтинг

Подборка нейросетей для генерации текстов и копирайтинга. Сервисы, которые помогают создавать статьи, посты и рекламные объявления с нуля или по черновику, экономя часы рутинной ра

NeuroscribeNeuroscribe
Есть бесплатный тариф
5.0
GoGPTGogpt
По запросу
5.0
ChatsonicChatsonic
По запросу
4.9
НейроТекстерNeuro-texter
По запросу
4.9
ChatGPTOpenAI
По подписке
4.9
Редактум
Есть бесплатный тариф
4.8
ChadGPTChadgpt
По запросу
4.8
Cosmo ScribeCosmoscribe
Есть бесплатный тариф
4.8
Memo HelperCopilot33
По запросу
4.8
LibraChatLibrachat
Есть бесплатный тариф
4.8