К основному содержанию
правило CX Codex

test-strategy — правило для Claude Code: тесты и установка

Правило test-strategy для Claude Code задаёт структуру тест-плана и требования к автотестам — от граничных случаев до проверки ошибок. Описывает тесты, добавляемые или изменяемые вместе с кодом.

MIT ★ 359 обновлён 2025-12-01

Установить в Claude Code · Вручную: положить файлы Все способы и платформы ↓
.claude/rules/test-strategy.md
Открыть на GitHub

Что делает test-strategy

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

Каждый сценарий из таблицы становится автотестом. Правило требует не меньше тестов на ошибки, чем на обычные случаи, комментарии Given/When/Then и проверку типа и сообщения исключения. Цель — 100% покрытия ветвей; если это недостижимо, нужно описать непокрытые ветви и их влияние. Для сбоев внешних зависимостей предусмотрены заглушки или моки.

В конце документации или PR нужно указать команду запуска и способ получить покрытие. Даже если внешних зависимостей нет, правило требует моделировать сбои с помощью моков. Для Claude Code файл устанавливают по пути .claude/rules/test-strategy.md; для Windsurf указан .devin/rules/test-strategy.md.

Какие задачи решает

  • составить таблицу тестовых сценариев до написания тестов
  • проверить граничные значения и некорректные входные данные
  • добавить автотесты для ошибок и сбоев зависимостей
  • зафиксировать непокрытые ветви и причины
  • описать запуск тестов и получение отчёта покрытия

Примеры запросов агенту

  • Составь таблицу сценариев для тестов этой функции, включая ошибки и граничные значения.
  • Добавь автотесты по таблице и проверь типы и сообщения исключений.
  • Укажи команду запуска тестов и способ получить покрытие в описании PR.

Как установить test-strategy

Вручную: положить файлы

.claude/rules/test-strategy.md

Поле paths во frontmatter ограничивает файлы

По шагам, с командами для каждой платформы: AGENTS.md и CLAUDE.md: что это, кто читает и какой выбрать

Вопросы о test-strategy

Как установить test-strategy в Claude Code?

Добавьте правило в проект по пути .claude/rules/test-strategy.md.

Что делает test-strategy?

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

Какие тестовые случаи требует test-strategy?

Нужны штатные, ошибочные и граничные случаи, а также проверки неверного типа или формата. Сбои API, базы данных и других внешних зависимостей проверяют, когда это применимо.

Исходный текст

test-strategy.md · MIT
---
trigger: model_decision
description: Applied when implementing or modifying test code. Rules for creating test perspective tables (equivalence partitioning/boundary values), Given/When/Then format, and coverage targets
globs:
---

## Test Strategy Rules

These rules define the testing process that must be followed when implementing or modifying test code. A test task is not considered complete unless all of the following steps are satisfied.

---

## 1. Test Perspective Table (Equivalence Partitioning / Boundary Values)

1. Before starting any test work, you must first present a "test perspectives table" in Markdown format.
2. The table must include at least the following columns: `Case ID`, `Input / Precondition`, `Perspective (Equivalence / Boundary)`, `Expected Result`, `Notes`.
3. Rows must cover normal cases, error cases, and boundary value cases. For boundary values, include at minimum `0 / minimum / maximum / ±1 / empty / NULL`.
   Boundary value candidates (0 / minimum / maximum / ±1 / empty / NULL) that have no meaning in the specification may be omitted with the reason stated in `Notes`.
4. If you notice missing perspectives later, update the table after self-review and add necessary cases.
5. Note that for minor modifications to existing tests (message adjustments, minor expected value corrections, etc.) where no new branches or constraints are added, creating/updating the test perspective table is optional.

### Template Example

| Case ID | Input / Precondition | Perspective (Equivalence / Boundary) | Expected Result                               | Notes |
|--------|----------------------|---------------------------------------|----------------------------------------------|-------|
| TC-N-01 | Valid input A        | Equivalence – normal                 | Processing succeeds and returns expected value | -     |
| TC-A-01 | NULL                 | Boundary – NULL                      | Validation error (required field)            | -     |
| ...     | ...                  | ...                                   | ...                                          | ...   |

---

## 2. Test Code Implementation Policy

1. Implement **all** cases listed in the above table as automated tests.
2. **Always include failure cases equal to or more than normal cases** (validation errors, exceptions, external dependency failures, etc.).
3. Cover the following perspectives in tests:
   - Normal cases (main scenarios)
   - Error cases (validation errors, exception paths)
   - Boundary values (0, minimum, maximum, ±1, empty, NULL)
   - Invalid type/format inputs
   - External dependency failures (API / DB / messaging, etc. when applicable)
   - Exception types and error messages
4. Furthermore, aim for 100% branch coverage and design additional cases yourself as needed.
   100% branch coverage is a target; if not reasonably achievable, at minimum cover branches with high business impact and main error paths.
   If there are uncovered branches, state the reason and impact in `Notes` or the PR body.

---

## 3. Given / When / Then Comments

Each test case must have the following comment format.

```text
// Given: Preconditions
// When:  Operation to execute
// Then:  Expected result/verification
```

Write comments directly above the test code or within steps to keep the scenario traceable for readers.

---

## 4. Exception/Error Verification

1. For cases where exceptions occur, explicitly verify the exception **type** and **message**.
2. For validation error cases, also verify error codes and field information if available.
3. When simulating external dependency failures, use stubs/mocks to verify that expected exceptions/retries/fallbacks are called.

---

## 5. Execution Commands and Coverage

1. At the end of test implementation, always document the **execution command** and **coverage acquisition method** at the end of documentation or PR body.
   - Examples: `npm run test`, `pnpm vitest run --coverage`, `pytest --cov=...`
2. Check branch coverage and statement coverage, aiming for 100% branch coverage (if not reasonably achievable, prioritize branches with high business impact and main error paths).
3. Attach coverage report verification results (screenshots or summaries) where possible.

---

## 6. Operational Notes

1. Test diffs that do not conform to this rule will be rejected in review.
2. Even when there are no external dependencies, **use mocks to simulate failures** for failure cases.
3. When new branches or constraints are added to the test target specification, update the test perspective table and test code simultaneously.
4. If there are cases that are difficult to automate, clearly state the reason and alternative means, and reach agreement with reviewers.
   Alternative means should include at minimum: target functionality and risks, manual verification procedures, expected results, and how to save logs or screenshots.
5. As a rule, PRs containing meaningful changes to production code (feature additions, bug fixes, refactoring that may affect behavior) must always include corresponding automated test additions or updates.
6. If adding/updating tests is reasonably difficult, clearly state the reason and alternative verification procedures (manual test procedures, etc.) in the PR body and reach agreement with reviewers.
7. Even for refactoring not intended to change behavior, verify that the changed areas are sufficiently covered by existing tests, and add tests if insufficient.

---

Follow this rule and always self-check for missing perspectives before designing and implementing tests.

© kinopeee · MIT · kinopeee/windsurf-antigravity-rules

Похожие правила IDE

Все правила IDE по теме «Тесты и QA» →
test-automation-strategy proffesor-for-testing Скилл test-automation-strategy проектирует стратегию автоматизации тестов, исправляет перекосы тестовой пирамиды и связывает проверки с CI/CD. CX Codex +1 261установок testing-strategy официальный anthropics Скилл testing-strategy для Claude Code проектирует стратегию тестирования и тест-план для компонента. Включается на вопросы о том, как тестировать и какие тесты нужны. CX Codex +1 6 800установок test-driven-development Jesse Vincent Скилл test-driven-development для Claude Code задаёт цикл TDD: тест, проверка падения, минимальный код и рефакторинг. Цикл охватывает новые функции, исправления и изменения поведения. CX Codex +1 259 292установок design-testing-strategy NeoLabHQ Скилл design-testing-strategy помогает решить, какие тесты писать под конкретный артефакт: юнит, интеграционные, контрактные, property-based или никакие. CX Codex +1 729установок dotnet-testing-strategy wshaddix Скилл dotnet-testing-strategy помогает ассистенту выбрать тип тестов для .NET-кода, структурировать папки в проекте и задать имена тестовым методам. Пригодится при проектировании архитектуры тестов. CX Codex +1 624установок momentic-test momentic-ai Скилл momentic-test для Claude Code создаёт и запускает тесты Momentic для браузера, Android и iOS. Он работает с YAML-файлами тестов и модулей. CX Codex +1 68 600установок

Из того же набора7

planning-mode-guard Правило planning-mode-guard запрещает ИИ менять рабочий код во время планирования и заставляет отвечать на языке пользователя. CX Codex +1 ★ 359звёзд репо pr-message-format Правило pr-message-format задаёт формат заголовка и структурированного описания Pull Request. Оно пригодится, когда агент готовит PR по изменениям в коде. CX Codex +1 ★ 359звёзд репо commit-message-format Правило commit-message-format для единообразных коммитов по Conventional Commits: префикс типа, краткая суть на английском и список изменений буллетами. CX Codex +1 ★ 359звёзд репо prompt-injection-guard Правило prompt-injection-guard останавливает агента перед опасной командой из внешнего источника и требует подтверждения, а не просто предупреждает и выполняет её. CX Codex +1 ★ 359звёзд репо v5 Правило v5 задаёт регламент написания кода: делит задачи на лёгкие, стандартные и критические, запрещает длинные предисловия и регулирует вызов инструментов. CX Codex +1 ★ 359звёзд репо v5 v5 задаёт порядок работы ИИ-ассистента над кодом: от мелких исправлений до критичных изменений. Помогает согласовать план, чтение файлов и проверки с масштабом задачи. CX Codex +1 ★ 359звёзд репо

Спонсоры проекта

Компании, которые помогают держать аналитику открытой