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

cucumber-best-practices — скилл для Claude Code: как поставить

Скилл cucumber-best-practices обучает ИИ-агента писать декларативные BDD-сценарии в Cucumber, избегать технического мусора в Gherkin и делить связанные тесты. Пригодится при рефакторинге автотестов.

Apache-2.0 154 установок ★ 201 обновлён 2026-09-08

Установить в Claude Code · Через Skills CLI (Vercel) Все способы и платформы ↓
npx skills add TheBushidoCollective/han --skill cucumber-best-practices -a claude-code
Открыть на GitHub

Что делает cucumber-best-practices

Скилл задаёт правила для синтаксиса Gherkin. Он направляет модель на составление декларативных сценариев на языке бизнеса вместо перечисления кликов по CSS-селекторам и ожидания AJAX-ответов. Сценарии выстраиваются по принципу изоляции: каждый тест готовит данные самостоятельно и проверяет строго одно поведение.

Внутри собраны шаблоны для секций Background, правила фильтрации прогонов через теги вроде @smoke или @wip, а также структура Scenario Outline с таблицами Examples. Скилл предостерегает от склеивания нескольких действий союзами «and» внутри одного шага и удерживает абстракцию шагов на едином уровне.

В конфигурации скилла задан параметр user-invocable: false. Вызывать его отдельной слэш-командой не нужно. Ассистент подтягивает правила сам при создании фича-файлов и определений шагов.

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

  • переписать императивные шаги с селекторами в декларативный Gherkin
  • разделить зависимые сценарии на изолированные тесты
  • сгруппировать наборы проверок тегами для выборочного запуска
  • оформить повторяющиеся проверки через Scenario Outline

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

  • Перепиши сценарий оформления заказа в декларативном стиле без упоминания CSS-селекторов.
  • Раздели этот связанный сценарий на независимые тесты для регистрации и входа.
  • Собери Scenario Outline с таблицей Examples для расчёта скидок по категориям клиентов.

Как установить cucumber-best-practices

1Через Skills CLI (Vercel)

npx skills add TheBushidoCollective/han --skill cucumber-best-practices -a claude-code

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

~/.claude/skills/cucumber-best-practices/SKILL.md

Папка скилла целиком; для одного проекта — .claude/skills/cucumber-best-practices/

По шагам, с командами для каждой платформы: Как установить скилл в Claude Code: пять способов

Вопросы о cucumber-best-practices

Как установить cucumber-best-practices в Claude Code?

Выполните в терминале команду npx skills add TheBushidoCollective/han --skill cucumber-best-practices -a claude-code. Конфигурация запишется в ~/.claude/skills/cucumber-best-practices/SKILL.md.

Зачем нужен скилл cucumber-best-practices?

Он задаёт шаблоны проектирования BDD-тестов. Ассистент перестаёт генерировать громоздкие технические шаги и пишет понятные бизнес-сценарии.

Можно ли вызвать скилл слэш-командой?

Нет, в манифесте указан параметр user-invocable: false. Модель обращается к этим правилам автоматически, когда создаёт или редактирует тесты Cucumber.

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

SKILL.md · Apache-2.0
---
name: cucumber-best-practices
user-invocable: false
description: Cucumber best practices, patterns, and anti-patterns
---

# Cucumber Best Practices

Master patterns and practices for effective Cucumber testing.

## Scenario Design Principles

### 1. Write Declarative Scenarios

Focus on **what** needs to happen, not **how** it happens.

❌ **Imperative** (implementation-focused):

```gherkin
Scenario: Add product to cart
  Given I navigate to "http://shop.com/products"
  When I find the element with CSS ".product[data-id='123']"
  And I click the button with class "add-to-cart"
  And I wait for the AJAX request to complete
  Then the element ".cart-count" should contain "1"
```

✅ **Declarative** (business-focused):

```gherkin
Scenario: Add product to cart
  Given I am browsing products
  When I add "Wireless Headphones" to my cart
  Then my cart should contain 1 item
```

### 2. One Scenario, One Behavior

Each scenario should test exactly one business rule or behavior.

❌ **Multiple behaviors in one scenario:**

```gherkin
Scenario: User registration and login and profile update
  Given I register a new account
  When I log in
  And I update my profile
  And I change my password
  Then everything should work
```

✅ **Separate scenarios:**

```gherkin
Scenario: Register new account
  When I register with valid details
  Then I should receive a confirmation email

Scenario: Login with new account
  Given I have registered an account
  When I log in with my credentials
  Then I should see my dashboard

Scenario: Update profile
  Given I am logged in
  When I update my profile information
  Then my changes should be saved
```

### 3. Keep Scenarios Independent

Each scenario should set up its own preconditions.

❌ **Dependent scenarios:**

```gherkin
Scenario: Create order
  When I create order #12345

Scenario: View order
  When I view order #12345  # Depends on previous scenario!
```

✅ **Independent scenarios:**

```gherkin
Scenario: View order
  Given an order exists with ID "12345"
  When I view the order details
  Then I should see the order information
```

### 4. Use Background Wisely

Use Background for common setup, but don't overuse it.

✅ **Good use of Background:**

```gherkin
Feature: Shopping Cart

  Background:
    Given I am logged in as a customer

  Scenario: Add product to cart
    When I add a product to my cart
    Then my cart should contain 1 item

  Scenario: Remove product from cart
    Given I have a product in my cart
    When I remove the product
    Then my cart should be empty
```

❌ **Background doing too much:**

```gherkin
Background:
  Given I am on the homepage
  And I click the menu
  And I navigate to products
  And I filter by category "Electronics"
  And I sort by price
  # Too much setup! Not all scenarios need all of this
```

## Feature Organization

### Group Related Scenarios

```gherkin
Feature: User Authentication

  Scenario: Successful login
    ...

  Scenario: Failed login with wrong password
    ...

  Scenario: Account lockout after multiple failures
    ...
```

### Use Tags Effectively

```gherkin
@smoke @critical
Scenario: Login with valid credentials
  ...

@slow @integration
Scenario: Password reset email workflow
  ...

@wip
Scenario: OAuth login
  # Work in progress
  ...
```

Run specific tags:

```bash
# Run smoke tests
cucumber --tags "@smoke"

# Run all except WIP
cucumber --tags "not @wip"

# Run smoke AND critical
cucumber --tags "@smoke and @critical"

# Run smoke OR critical
cucumber --tags "@smoke or @critical"
```

## Writing Good Gherkin

### Use Domain Language

Write in the language of the business domain, not technical terms.

❌ **Technical language:**

```gherkin
Scenario: POST request to /api/users
  When I send a POST to "/api/users" with JSON payload
  And the response status is 201
```

✅ **Domain language:**

```gherkin
Scenario: Register new user
  When I register a new user account
  Then the user should be created successfully
```

### Keep Steps at the Same Level

Don't mix high-level and low-level details.

❌ **Mixed levels:**

```gherkin
Scenario: Purchase product
  Given I am logged in
  When I add a product to cart
  And I click the element with ID "checkout-btn"  # Too detailed!
  And I enter credit card "4111111111111111"      # Too detailed!
  Then I complete the purchase
```

✅ **Consistent level:**

```gherkin
Scenario: Purchase product
  Given I am logged in
  And I have a product in my cart
  When I checkout with a credit card
  Then my order should be completed
  And I should receive a confirmation email
```

### Avoid Conjunctive Steps

Don't use "And" to combine multiple distinct actions in prose.

❌ **Conjunctive step:**

```gherkin
When I log in and add a product to cart and checkout
```

✅ **Separate steps:**

```gherkin
When I log in
And I add a product to my cart
And I proceed to checkout
```

## Scenario Outlines

### Use for True Variations

Use Scenario Outlines when you need to test the same behavior with different data.

✅ **Good use:**

```gherkin
Scenario Outline: Login validation
  When I log in with "<username>" and "<password>"
  Then I should see "<message>"

  Examples:
    | username | password | message                |
    | valid    | valid    | Welcome                |
    | invalid  | valid    | Invalid username       |
    | valid    | invalid  | Invalid password       |
    | empty    | empty    | Username required      |
```

❌ **Overusing Scenario Outline:**

```gherkin
# Don't use Scenario Outline for unrelated test cases
Scenario Outline: Multiple features
  When I use feature "<feature>"
  Then result is "<result>"

  Examples:
    | feature        | result    |
    | login          | success   |
    | registration   | success   |
    | cart           | empty     |  # These are different behaviors!
```

### Keep Examples Meaningful

```gherkin
Scenario Outline: Discount calculation
  Given a customer with "<membership>" status
  When they purchase items totaling $<amount>
  Then they should receive a $<discount> discount

  Examples: Standard discounts
    | membership | amount | discount |
    | silver     | 100    | 5        |
    | gold       | 100    | 10       |
    | platinum   | 100    | 15       |

  Examples: Minimum purchase thresholds
    | membership | amount | discount |
    | silver     | 49     | 0        |
    | silver     | 50     | 2.50     |
```

## Step Definition Patterns

### Create Reusable Steps

```javascript
// Generic, reusable
When('I fill in {string} with {string}', async function(field, value) {
  await this.page.fill(`[name="${field}"]`, value);
});

// Used in multiple scenarios:
When('I fill in "email" with "[email protected]"')
When('I fill in "password" with "secure123"')
When('I fill in "search" with "products"')
```

### Avoid Over-Generic Steps

Balance reusability with readability.

❌ **Too generic:**

```javascript
When('I do {string} with {string} and {string}', ...)
```

✅ **Specific and readable:**

```javascript
When('I log in with {string} and {string}', ...)
When('I search for {string} in {string}', ...)
```

## Data Management

### Use Factories for Test Data

```javascript
// support/factories.js
const faker = require('faker');

class UserFactory {
  static create(overrides = {}) {
    return {
      firstName: faker.name.firstName(),
      lastName: faker.name.lastName(),
      email: faker.internet.email(),
      password: 'Test123!',
      ...overrides
    };
  }
}

// Use in steps
Given('I register a new user', async function() {
  const user = UserFactory.create();
  this.currentUser = user;
  await this.api.register(user);
});
```

### Avoid Hardcoded IDs

❌ **Hardcoded:**

```gherkin
Given user "12345" exists
When I view order "67890"
```

✅ **Named entities:**

```gherkin
Given a user "[email protected]" exists
When I view my most recent order
```

## Error Handling

### Test Happy and Unhappy Paths

```gherkin
@happy-path
Scenario: Successful checkout
  Given I have items in my cart
  When I complete the checkout process
  Then my order should be confirmed

@error-handling
Scenario: Checkout with expired card
  Given I have items in my cart
  When I checkout with an expired credit card
  Then I should see an error message
  And my order should not be processed

@edge-case
Scenario: Checkout with insufficient inventory
  Given I have a product in my cart
  But the product is out of stock
  When I attempt to checkout
  Then I should be notified about stock unavailability
```

## Performance

### Tag Slow Tests

```gherkin
@slow @integration
Scenario: Full order workflow with email notifications
  # Takes 30 seconds to run
  ...
```

### Parallel Execution

Ensure scenarios can run in parallel:

```javascript
// cucumber.js
module.exports = {
  default: '--parallel 4'
};
```

## Maintenance

### Regular Review

- Remove obsolete scenarios
- Update scenarios when requirements change
- Refactor duplicate steps
- Keep features organized

### Version Control

```
features/
  authentication/
    login.feature
    registration.feature
  shopping/
    cart.feature
    checkout.feature
  admin/
    user-management.feature
```

## Common Anti-Patterns

❌ **Testing implementation details:**

```gherkin
Then the database should have 1 record in the users table
```

❌ **UI-specific assertions in business scenarios:**

```gherkin
Then I should see a red error message in the top right corner
```

❌ **Using Given for actions:**

```gherkin
Given I click the submit button  # This is a When, not a Given!
```

❌ **Technical jargon:**

```gherkin
When I POST to /api/v1/users with JSON body
```

## Testing Pyramid

Use Cucumber appropriately in your test strategy:

- **E2E Cucumber Tests**: Critical user journeys (20%)
- **Integration Tests**: API/service interactions (30%)
- **Unit Tests**: Business logic (50%)

Don't try to test everything with Cucumber. Use it for high-value acceptance tests.

Remember: Cucumber tests should document behavior, facilitate collaboration, and provide confidence that the system works as expected from a business perspective.

© TheBushidoCollective · Apache-2.0 · TheBushidoCollective/han

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

Все скиллы по теме «Тесты и QA» →
add-cucumber-tests Decathlon Скилл add-cucumber-tests превращает функциональную спецификацию в .feature-файлы Cucumber, опираясь на реальные step definitions из Tzatziki. Пригодится в Java/Spring-проектах, где уже есть зависимости Tzatziki или Cucumber. CX Codex +1 1 100установок cucumber-skill TestMu AI Создаёт сценарии Cucumber на Gherkin и связанные step definitions. Он описывает поведение приложения через BDD-сценарии. CX Codex +1 283установок gherkin-style-testing-cursorrules-prompt-file PatrickJS Правило gherkin-style-testing-cursorrules-prompt-file превращает технические тест-скрипты и ручные кейсы в Gherkin-сценарии на языке, понятном бизнесу и юристам. CX Codex +1 ★ 41 178звёзд репо qa-planning WellApp-ai Скилл qa-planning собирает QA-контракт по фиче: нумерованные Gherkin-сценарии для источников данных и приёмочные критерии для фронтенда. Пригодится до начала реализации. CX Codex +1 1установок behavior-driven-development FradSer Скилл behavior-driven-development задаёт BDD-процесс для фич, исправлений и тестов: сначала сценарий и падающий тест, затем код. CX Codex +1 151установок serenity-bdd-skill TestMu AI serenity-bdd-skill — скилл для Claude Code, который создаёт BDD-тесты на Java с Serenity и паттерном Screenplay. Запускается при запросах о Serenity, @Steps или отчётах Serenity. CX Codex +1 223установок

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

Весь набор →
bdd-scenarios Скилл bdd-scenarios для Claude Code описывает поведение системы через BDD-сценарии, критерии приёмки и крайние случаи. Помогает согласовать требования до реализации. CX Codex +1 180установок playwright-bdd-gherkin-syntax Скилл playwright-bdd-gherkin-syntax помогает составлять feature-файлы Gherkin для Playwright BDD с учётом сценариев, таблиц примеров и тегов. CX Codex +1 180установок storybook-component-documentation Скилл storybook-component-documentation генерирует документацию компонентов в Storybook через autodocs, MDX-страницы и JSDoc-комментарии. Пригодится при создании или обновлении доков для UI-библиотек. CX Codex +1 166установок sop-maintenance Скилл sop-maintenance для Claude Code обновляет, версионирует и выводит из эксплуатации стандартные операционные процедуры (SOP). Обновляет регламенты после смены стека. CX Codex +1 159установок android-kotlin-coroutines Скилл android-kotlin-coroutines для Claude Code задаёт шаблоны корутин и Flow для Android. Помогает настраивать асинхронную работу во ViewModel, репозиториях и Jetpack Compose без утечек памяти. CX Codex +1 145установок ios-uikit-architecture Скилл ios-uikit-architecture с паттернами архитектуры UIKit: MVVM, MVC, координаторы, dependency injection и способы встроить SwiftUI в UIKit-приложение. Пригодится при разработке iOS-приложений на UIKit. CX Codex +1 145установок android-architecture Скилл android-architecture для Claude Code помогает проектировать Android-приложения по MVVM и clean architecture. Описывает слои data, domain и presentation, Hilt и Room. CX Codex +1 141установок reactflow-fundamentals Скилл reactflow-fundamentals помогает создавать блок-схемы, редакторы пайплайнов и графы на React Flow. Подсказывает агенту готовые структуры узлов, рёбер и элементов управления. CX Codex +1 138установок

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

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