Перейти к содержанию
Skillpedia
Тестирование260k · #626

test-driven-development

Что он делает

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

Когда использовать

  • ✓Когда вы просите ИИ добавить новую функцию или изменить поведение кода.
  • ✓Когда вы просите ИИ исправить ошибку и хотите тест, который подтверждает исправление.
  • ✓Когда вы хотите безопасно переписать код, имея тесты.

Ссылка на скилл

https://github.com/NousResearch/hermes-agent/blob/main/skills/software-development/test-driven-development/SKILL.md

Скопируйте и вставьте её в ваш ИИ (Claude, ChatGPT или Cursor) с просьбой следовать инструкциям.

Как использовать

Самый простой способ: скопируйте сообщение и вставьте его в свой ИИ. Он прочитает скилл и выполнит инструкции.

Готовое сообщение для вставки

Используй этот скилл, чтобы помочь мне: https://github.com/NousResearch/hermes-agent/blob/main/skills/software-development/test-driven-development/SKILL.md Прочитай файл SKILL.md по этой ссылке и следуй его инструкциям в моей задаче.
Хотите, чтобы ваш ИИ сам находил такие скиллы?Установите бесплатный MCP Skillpedia: одна строка, и перед каждой задачей он ищет среди 15 000+ скиллов.Установить за 1 минуту →

Пример запроса к вашему ИИ

“Добавь функцию повторной попытки в нашу функцию загрузки и напиши сначала тест, чтобы мы знали, что она работает.”

5 новых скиллов в неделю. 1 минута чтения.

Как это работает

Скилл следует циклу «красный — зелёный — рефакторинг»: пишется один небольшой тест, который смотрят падающим, затем пишется минимум кода, чтобы он прошёл, и код приводится в порядок. ИИ удаляет любой код, написанный до падающего теста.

Технический текст (оригинальный SKILL.md)

Оригинальный текст автора на английском, прямо с GitHub.

Test-Driven Development (TDD)

Overview

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

Core principle: If you didn't watch the test fail, you don't know if it tests 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 (ask the user first):

  • Throwaway prototypes
  • Generated code
  • Configuration files

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.

Red-Green-Refactor Cycle

RED — Write Failing Test

Write one minimal test showing what should happen.

Good test:

def test_retries_failed_operations_3_times():
    attempts = 0
    def operation():
        nonlocal attempts
        attempts += 1
        if attempts < 3:
            raise Exception('fail')
        return 'success'

    result = retry_operation(operation)

    assert result == 'success'
    assert attempts == 3

Clear name, tests real behavior, one thing.

Bad test:

def test_retry_works():
    mock = MagicMock()
    mock.side_effect = [Exception(), Exception(), 'success']
    result = retry_operation(mock)
    assert result == 'success'  # What about retry count? Timing?

Vague name, tests mock not real code.

Requirements:

  • One behavior per test
  • Clear descriptive name ("and" in name? Split it)
  • Real code, not mocks (unless truly unavoidable)
  • Name describes behavior, not implementation

Verify RED — Watch It Fail

MANDATORY. Never skip.

# Use terminal tool to run the specific test
pytest tests/test_feature.py::test_specific_behavior -v

Confirm:

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

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

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

GREEN — Minimal Code

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

Good:

def add(a, b):
    return a + b  # Nothing extra

Bad:

def add(a, b):
    result = a + b
    logging.info(f"Adding {a} + {b} = {result}")  # Extra!
    return result

Don't add features, refactor other code, or "improve" beyond the test.

Cheating is OK in GREEN:

  • Hardcode return values
  • Copy-paste
  • Duplicate code
  • Skip edge cases

We'll fix it in REFACTOR.

Verify GREEN — Watch It Pass

MANDATORY.

# Run the specific test
pytest tests/test_feature.py::test_specific_behavior -v

# Then run ALL tests to check for regressions
pytest tests/ -q

Confirm:

  • Test passes
  • Other tests still pass
  • Output pristine (no errors, warnings)

Test fails? Fix the code, not the test.

Other tests fail? Fix regressions now.

REFACTOR — Clean Up

After green only:

  • Remove duplication
  • Improve names
  • Extract helpers
  • Simplify expressions

Keep tests green throughout. Don't add behavior.

If tests fail during refactor: Undo immediately. Take smaller steps.

Repeat

Next failing test for next behavior. One cycle at a time.

Avoid Horizontal Slices

Do not write all tests first and then all implementation. That is horizontal slicing: RED becomes "write a pile of imagined tests" and GREEN becomes "make the pile pass." It produces brittle tests because the tests are designed before the implementation has taught you what behavior and interface actually matter.

Use vertical tracer bullets instead:

WRONG:
  RED:   test1, test2, test3, test4
  GREEN: impl1, impl2, impl3, impl4

RIGHT:
  RED→GREEN: test1→impl1
  RED→GREEN: test2→impl2
  RED→GREEN: test3→impl3

A tracer bullet is one end-to-end behavior slice. It proves the path works, teaches you about the interface, and keeps each next test grounded in what you just learned.

Why Order Matters

"I'll write tests after to verify it works"

Tests written after code pass immediately. Passing immediately proves nothing:

  • Might test the wrong thing
  • Might test implementation, not behavior
  • Might miss edge cases you forgot
  • You never saw it catch the bug

Test-first forces you to see the test fail,

Частые вопросы

Есть ли исключения?

Да. Скилл говорит сначала спрашивать для одноразовых прототипов, сгенерированного кода и конфигурационных файлов.

Почему тест обязательно должен упасть сначала?

Скилл говорит, что если вы не видели, как тест падает, вы не знаете, проверяет ли он нужное.

Что делать, если код уже написан?

Скилл советует удалить код и начать заново с тестов.

Подробности

Оригинальное описание автора

TDD: enforce RED-GREEN-REFACTOR, tests before code.

repo: NousResearch/hermes-agent

Популярность

Звёзды на GitHub
260k
Место в рейтинге
#626
Лицензия
MIT
Обновлён
02.11.2026

Полезен ли этот скилл?

0

Войдите , чтобы голосовать.

Комментарии

  • …

Другие скиллы из этого репозитория

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