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

principle-test-behavior-not-implementation

Что он делает

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

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

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

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

https://github.com/cursor/plugins/blob/main/harness/pstack/claude-code/skills/principle-test-behavior-not-implementation/SKILL.md

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

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

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

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

Используй этот скилл, чтобы помочь мне: https://github.com/cursor/plugins/blob/main/harness/pstack/claude-code/skills/principle-test-behavior-not-implementation/SKILL.md Прочитай файл SKILL.md по этой ссылке и следуй его инструкциям в моей задаче.
Хотите, чтобы ваш ИИ сам находил такие скиллы?Установите бесплатный MCP Skillpedia: одна строка, и перед каждой задачей он ищет среди 15 000+ скиллов.Установить за 1 минуту →

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

“Наши тесты ломаются при каждом рефакторинге, даже когда ничего видимого пользователю не менялось. Перепиши их, чтобы они проверяли поведение.”

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

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

Ассистент проверяет каждый тест на двух воображаемых правках: одна ломает поведение, и тест обязан её поймать, другая меняет только внутренности, и тест обязан её пережить. Тесты, которые не проходят любую из проверок, он переписывает или удаляет, обращаясь к коду через публичный интерфейс.

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

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

Test Behavior, Not Implementation

A test is a claim about what the code does for its users: a caller, an end user, or another service. Behavior is what those users can observe through the interface they use. That includes return values, errors, state they can read back, and effects on systems outside the code, such as a request sent, a row written, or a message emitted. Implementation is what they cannot observe: private helpers, internal call order, intermediate data, and which internal collaborator did the work.

Judge each test against two imagined edits:

  • Break the behavior. Make the code return a wrong value, skip an effect, or do the effect twice. If the test still passes, it proves nothing. The usual causes are an assertion looser than the contract, an expected value computed by the code under test, a restated constant or prompt string that never runs the code that reads it, and an assertion on data that the test built itself.
  • Change the internals. Keep every observable result the same and restructure the code underneath. If the test now fails, it is pinned to the implementation. It will need a rewrite on every refactor and still catches no bug.

Keep a test that catches the first edit and survives the second. Rewrite or delete the rest. To write a test that does both, drive the code through its users' interface with a concrete input. Derive the expected value from the requirement, not from a run of the code. Assert what the contract promises, no less and no more.

The contract decides, not the shape of the assertion. When "an empty cart never charges" is the promise, an assertion that the payment client got no call is behavior. Pair it with a case where the charge happens, so that the test shows it can see a call. The payload that a mocked external service receives is behavior, because that service observes it. A call to an internal helper is implementation, because no user can see it. An empty list is the exact answer when no record matches, and a hollow check when the test only needs some result. An exact error message pins wording that no caller reads. The error type that callers branch on is the contract.

A test can pin an invariant instead of a call, such as a key that must exist in two tables or a compile-time type check. The invariant is the behavior.

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

Что считается поведением?

То, что видят пользователи кода: возвращаемые значения, ошибки, читаемое состояние и эффекты, например отправленное сообщение.

Что такое слабый тест?

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

Нужно ли тестировать приватные функции?

Нет. Приватные функции и порядок внутренних вызовов относятся к деталям реализации, а не к поведению.

Подробности

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

Apply when you write, change, or keep a test. Assert what the code's users can observe, so that the test fails when that behavior breaks and keeps passing when only the internals change.

repo: cursor/plugins

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

Звёзды на GitHub
15k
Место в рейтинге
#10990
Лицензия
—
Обновлён
31.10.2026

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

0

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

Комментарии

  • …

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

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