Command Palette

Search for a command to run...

UnylyUnyly
Назад к скиллам

TDD Patterns

БесплатноБез исполняемых скриптовНе проверен

Practice strict red-green-refactor test-driven development — write one failing test first, make it pass with the minimum code, then refactor under green, with…

PramodDuttaот PramodDutta★ 253 звезды на GitHub

Об этом скилле

TDD Patterns

This skill makes an AI agent develop features test-first: write exactly one failing test, watch it fail for the right reason, write the minimum production code to pass, then refactor while green. It enforces the discipline most "TDD" sessions skip — never writing production code without a failing test demanding it. Trigger it when the user asks for TDD, test-first development, or when implementing new logic in a codebase that already has a test runner wired up.

Core Principles

  1. One failing test at a time. Not a suite of ten pending tests — one. Multiple red tests mean you are designing in your head instead of letting tests drive.
  2. Watch the test fail before making it pass. A test you never saw red might be passing vacuously (wrong assertion, testing the mock, typo'd import). The red step verifies the test itself.
  3. Write the minimum code that passes — even if it is embarrassingly dumb. Returning a hardcoded value is legal; the next test forces the generalization. "Fake it till the tests make you make it."
  4. Refactor only on green, and refactor both sides. Production code and test code rot equally. Duplication in tests is a design smell exactly as it is in src/.
  5. Test behavior through the public API, never internals. If renaming a private method breaks tests, the tests are coupled to implementation and will resist every refactor instead of enabling it.
  6. Name tests as behavioral sentences. rejects expired coupons at the boundary minute tells the next reader the rule; test_coupon_3 tells them nothing.
  7. The cycle is minutes, not hours. If you have been red for 20 minutes, the step was too big — delete, take a smaller bite.

Workflow: One Full Cycle in Jest (TypeScript)

Feature: a PriceCalculator that applies tiered bulk discounts.

RED — write the smallest failing test:

// src/price-calculator.test.ts
import { describe, expect, it } from '@jest/globals';
import { calculateTotal } from './price-calculator';

describe('calculateTotal', () => {
  it('returns unit price times quantity with no discount under 10 units', () => {
    // Arrange
    const unitPrice = 4.0;
    const quantity = 3;

    // Act
    const total = calculateTotal(unitPrice, quantity);

    // Assert
    expect(total).toBe(12.0);
  });
});
npx jest price-calculator
# FAIL — Cannot find module './price-calculator'  <- failing for the RIGHT reason

GREEN — minimum code, no speculation:

// src/price-calculator.ts
export function calculateTotal(unitPrice: number, quantity: number): number {
  return unitPrice * quantity;
}

RED again — the next test forces the discount rule:

it('applies a 10 percent discount at 10 units or more', () => {
  expect(calculateTotal(4.0, 10)).toBe(36.0); // 40 - 10%
});

it('applies a 20 percent discount at 50 units or more', () => {
  expect(calculateTotal(2.0, 50)).toBe(80.0); // 100 - 20%
});

GREEN:

export function calculateTotal(unitPrice: number, quantity: number): number {
  const subtotal = unitPrice * quantity;
  if (quantity >= 50) return subtotal * 0.8;
  if (quantity >= 10) return subtotal * 0.9;
  return subtotal;
}

REFACTOR — under green, extract the tier table:

const DISCOUNT_TIERS: ReadonlyArray<{ minQty: number; multiplier: number }> = [
  { minQty: 50, multiplier: 0.8 },
  { minQty: 10, multiplier: 0.9 },
  { minQty: 0, multiplier: 1.0 },
];

export function calculateTotal(unitPrice: number, quantity: number): number {
  const tier = DISCOUNT_TIERS.find((t) => quantity >= t.minQty)!;
  return unitPrice * quantity * tier.multiplier;
}

Run the suite after the refactor. Still green, behavior unchanged, structure improved. That is one complete cycle.

Workflow: Same Discipline in pytest

Feature: a password strength validator, driven boundary-first.

# tests/test_password_policy.py
import pytest

from app.password_policy import validate


class TestValidate:
    def test_rejects_passwords_shorter_than_12_chars(self):
        # Arrange / Act
        result = validate("Short1!aaaa")  # 11 chars

        # Assert
        assert result.ok is False
        assert "at least 12 characters" in result.errors

    def test_accepts_a_12_char_password_meeting_all_rules(self):
        result = validate("Sturdy-Pass1")  # exactly 12

        assert result.ok is True
        assert result.errors == []
pytest tests/test_password_policy.py -x
# ModuleNotFoundError: No module named 'app.password_policy'  <- correct red

Minimum green:

# app/password_policy.py
from dataclasses import dataclass, field


@dataclass
class Result:
    ok: bool
    errors: list[str] = field(default_factory=list)


def validate(password: str) -> Result:
    if len(password) < 12:
        return Result(ok=False, errors=["at least 12 characters"])
    return Result(ok=True)

Next red drives the remaining r

Полный SKILL.md на GitHub

Установить TDD Patterns в Claude Code и Claude Desktop

Зарегайся, чтобы установить скилл

Создай бесплатный аккаунт, чтобы открыть команду установки и сохранить скилл в библиотеку.

  • Открой команду установки в одну строку
  • Сохраняй скиллы в синхронизируемую библиотеку
  • Уведомления, когда скиллы обновляются
Зарегаться бесплатноУ меня уже есть аккаунт

Разрешённые инструменты

Инструменты, которые скиллу разрешено вызывать.

Без ограничений — скилл может использовать любой инструмент.

FAQ

Что делает скилл TDD Patterns?

Practice strict red-green-refactor test-driven development — write one failing test first, make it pass with the minimum code, then refactor under green, with worked cycles in Jest and pytest, AAA structure, and behavior-based test naming.

Как установить скилл TDD Patterns?

Скопируй папку скилла в ~/.claude/skills (вкладка Claude Code выше делает это одной командой), либо поставь как плагин.

Скилл TDD Patterns запускает скрипты?

Нет, скилл состоит только из инструкций (SKILL.md), без исполняемых скриптов.

Похожие скиллы

Сравнить TDD Patterns с