跳至正文
OpenAgentSkill
浏览已开放 · 目录记录日期 2026-11-21 · 自动更新和账户服务暂时关闭。
开发与测试

implement-with-tdd

Enforces test-driven development for feature work, bug fixes, and refactoring, activating for requests such as "implement", "fix", "add feature", "write tests first", or "TDD".

Codagent-AI · 已有静态检查记录

安装与使用

运行命令前先阅读来源与依赖说明。复制命令不会自动安装或执行。

npx skills add Codagent-AI/agent-skills --skill implement-with-tdd

技能说明


name: implement-with-tdd description: > Enforces test-driven development for feature work, bug fixes, and refactoring, activating for requests such as "implement", "fix", "add feature", "write tests first", or "TDD".

Test-Driven Development (TDD)

Overview

Write the test first. Watch it fail. Write minimal code to pass.

Core principle: Watch the test fail. Only then is it proven to test the right thing.

Violating the letter of the rules is violating the spirit of the rules.

When to Use

Always:

  • New features
  • Bug fixes
  • Refactoring
  • Behavior changes

Exceptions (skip TDD only for these; otherwise follow the full TDD cycle):

  • Throwaway spikes that will never be merged (branch must be deleted before implementation begins; any code carried forward requires full TDD)
  • Generated code (scaffolded, not behavior-bearing)
  • Configuration-only changes

Thinking "skip TDD just this once"? Stop. That's rationalization.

The Iron Law

NO PRODUCTION CODE WITHOUT A FAILING TEST FIRST

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

No exceptions:

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

Implement fresh from tests. Period.

Choosing Test Type

Honor any integration or E2E coverage explicitly required by the task's supplied requirements or test plan. For behavior without a higher-layer requirement, prove it at the lowest layer that can adequately detect the relevant failure:

  • Unit — pure logic, validation, transformations, calculations. No I/O, no wiring. Fast (<100ms).
  • Integration — components wired together: database queries, middleware chains, API clients, config reaching runtime. If the bug would only manifest when components connect, it needs an integration test.
  • E2E — critical user flows only (login, checkout, onboarding). Expensive, slow, flaky-prone. Don't use for logic that can be tested at a lower level.

Do not substitute a unit test for required integration or E2E coverage, and do not duplicate the same assertion at multiple layers without a distinct risk. When implementation tasks are supplied, keep each automated obligation in the same task as the behavior it protects.

When in doubt: can you test it with a function call and an assertion? Unit test. Does the risk exist only when real components connect? Integration test. Does only a complete public journey prove it? E2E test.

From Spec to Tests

Trace each specification scenario to automated coverage and write the relevant failing test before implementation. A scenario normally becomes one focused test at the lowest adequate layer, but an explicit integration or E2E requirement controls when higher-layer coverage is required. Do not reproduce the same scenario mechanically at every layer.

Spec scenario:

WHEN a user with an expired session requests a protected resource THEN they receive a 401 and a redirect to login

Test:

test('expired session returns 401 with login redirect', async () => {
  const session = createExpiredSession();
  const response = await requestProtectedResource(session);
  expect(response.status).toBe(401);
  expect(response.headers.location).toBe('/login');
});

One test per scenario, one scenario per behavior. If a scenario needs multiple assertions, that's fine — but if it needs multiple setups, split it. If the spec numbers its criteria (AC-1, R-001, etc.), reference the ID in the test name or comment for traceability. (Note: the spec skill does not generate IDs by default — IDs are an optional custom extension you may add to your spec for traceability.)

Red-Green-Refactor

digraph tdd_cycle {
    rankdir=LR;
    red [label="RED\nWrite failing test", shape=box, style=filled, fillcolor="#ffcccc"];
    verify_red [label="Verify fails\ncorrectly", shape=diamond];
    green [label="GREEN\nMinimal code", shape=box, style=filled, fillcolor="#ccffcc"];
    verify_green [label="Verify passes\nAll green", shape=diamond];
    refactor [label="REFACTOR\nClean up", shape=box, style=filled, fillcolor="#ccccff"];
    next [label="Next", shape=ellipse];

    red -> verify_red;
    verify_red -> green [label="yes"];
    verify_red -> red [label="wrong\nfailure"];
    green -> verify_green;
    verify_green -> refactor [label="yes"];
    verify_green -> green [label="no"];
    refactor -> verify_green [label="stay\ngreen"];
    verify_green -> next;
    next -> red;
}

RED - Write Failing Test

Write one minimal test showing what should happen.

Good:

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, tests real behavior, one thing

Bad:

test('retry works', async () => {
  const mock = jest.fn()
    .mockRejectedValueOnce(new Error())
    .mockRejectedValueOnce(new Error())
    .mockResolvedValueOnce('success');
  await retryOperation(mock);
  expect(mock).toHaveBeenCalledTimes(3);
});

Vague name, tests mock not code

Requirements:

  • One behavior
  • Clear name
  • Real code (no mocks unless unavoidable)

Verify RED - Watch It Fail

MANDATORY. Never skip.

npm test path/to/test.test.ts

Confirm:

  • Test fails (not errors)
  • Failure message is expected
  • Fails because feature missing (not typos)

Test passes? You're testing existing behavior. Fix test.

Test errors? Fix error, re-run until it fails correctly.

GREEN - Minimal Code

Write simplest code to pass the test.

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;
阅读完整来源 ↗