The post has been translated automatically. Original language: Russian
This is the seventh installment of the BDD series. In the sixth part, "BDD and the test pyramid: what to check at what level," we figured out where to run the scripts. In the eighth, "Implementing BDD in a team: where to start and how to evaluate the result," we'll talk about implementation.
BDD is often enthusiastically implemented, and after six months the scripts turn into a heavy set of fragile tests that no one reads. Let's look at the most common causes.
1. BDD without discussion
Symptom: scripts are written by a single tester or developer based on the finished requirements text.
The problem: the main value of the approach is lost. That leaves the usual tests with a different syntax.
What to do: spend the "three amigos" before implementation, at least for a short time.
2. UI scripts in the form of Gherkin
"Symptom": ""presses a button", "enters a field", "waits 3 seconds" in the scenarios.
The problem: any design change breaks the test suite, and the business cannot read such scenarios.
What to do: describe the rules declaratively, put the details in steps.
3. Too many scenarios
The symptom: there are hundreds of almost identical scenarios that differ by one value.
The problem: the run is growing, support is becoming more expensive, and it is impossible to find the right one.
What to do: use the script Structure with a table of examples, delete duplicates, check each rule once at the required level.
4. Dependent Scenarios
Symptom: Scenario 5 only works after scenario 4.
Problem: one failed test knocks down the rest, the launch order becomes mandatory.
What to do: each script creates the context it needs by itself (as given) and leaves no traces.
5. Logic in steps
Symptom: step definitions contain calculations, branches, and loops.
Problem: The tests duplicate the system's code and may make mistakes just like it.
What to do: The steps only prepare the data, call the system, and verify the result.
6. Automation of everything
The symptom: any requirement, even a technical one, turns into a scenario.
Problem: BDD is beginning to be perceived as a bureaucracy.
What to do: Leave BDD for business-relevant rules. Check the technical details with unit tests.
7. Scripts are not updated
The symptom is that the requirements have changed, and the .feature files have remained old or disabled.
The problem: the documentation is lying, and the credibility of the tests is falling.
What to do: change the script as part of the task. If the behavior has changed, the example is updated first.
Example: a bad and a good scenario
Bad:
Scenario: Checking the promo code
Given, the user opened the site
And logged in under a test account
And added the product to the cart
And went to the shopping cart
"""""""" When he enters "PROMO10" and clicks "Apply"
, then "9000" is displayed in the "Total"
field and the text color is green.Good:
Scenario: A valid promo code reduces the order amount
There are items in the basket for the amount of 10000 tenge
When a user applies a promo code for a 10 discount%
Then the order amount becomes 9,000 tengeIn the second version, there is no interface or unnecessary details. It is clear which rule is being checked here.
Result
Most of the problems with BDD are not related to tools, but to discipline: they forgot the discussion, got carried away with the UI, and expanded the set. In the eighth part, "Implementing BDD in a team: where to start and how to evaluate the result," we'll look at how to implement the approach without repeating these mistakes.
Which of these problems have you encountered? Which antipattern was the most unexpected?
Это седьмая часть серии о BDD. В шестой части, «BDD и тестовая пирамида: что на каком уровне проверять», мы разобрали, где запускать сценарии. В восьмой, «Внедрение BDD в команде: с чего начать и как оценить результат», поговорим о внедрении.
BDD часто внедряют с энтузиазмом, а через полгода сценарии превращаются в тяжёлый набор хрупких тестов, который никто не читает. Разберём самые частые причины.
1. BDD без обсуждения
Симптом: сценарии пишет один тестировщик или разработчик по готовому тексту требований.
Проблема: теряется главная ценность подхода. Остаются обычные тесты с другим синтаксисом.
Что делать: проводить «три амиго» до реализации, хотя бы короткие.
2. UI-скрипты в виде Gherkin
Симптом: в сценариях «нажимает кнопку», «вводит в поле», «ожидает 3 секунды».
Проблема: любое изменение дизайна ломает набор тестов, а бизнес не может читать такие сценарии.
Что делать: описывать правила декларативно, детали выносить в шаги.
3. Слишком много сценариев
Симптом: сотни почти одинаковых сценариев, отличающихся одним значением.
Проблема: прогон растёт, поддержка дорожает, найти нужное невозможно.
Что делать: использовать Структуру сценария с таблицей примеров, удалять дубли, проверять каждое правило один раз на нужном уровне.
4. Зависимые сценарии
Симптом: сценарий 5 работает только после сценария 4.
Проблема: один упавший тест валит остальные, порядок запуска становится обязательным.
Что делать: каждый сценарий создаёт нужный ему контекст сам (в Дано) и не оставляет следов.
5. Логика в шагах
Симптом: step definitions содержат вычисления, ветвления и циклы.
Проблема: тесты дублируют код системы и могут ошибаться так же, как он.
Что делать: шаги только подготавливают данные, вызывают систему и проверяют результат.
6. Автоматизация всего подряд
Симптом: любое требование, даже техническое, превращается в сценарий.
Проблема: BDD начинают воспринимать как бюрократию.
Что делать: оставлять BDD для правил, значимых для бизнеса. Технические детали проверять юнит-тестами.
7. Сценарии не обновляются
Симптом: требования изменились, а .feature-файлы остались старыми или отключены.
Проблема: документация лжёт, доверие к тестам падает.
Что делать: менять сценарий как часть задачи. Если поведение поменялось, сначала обновляется пример.
Пример: плохой и хороший сценарий
Плохо:
Сценарий: Проверка промокода
Дано пользователь открыл сайт
И залогинился под тестовым аккаунтом
И добавил товар в корзину
И перешёл в корзину
Когда он вводит "PROMO10" и нажимает "Применить"
Тогда в поле "Итого" отображается "9000"
И цвет текста зелёныйХорошо:
Сценарий: Действующий промокод снижает сумму заказа
Дано в корзине товары на сумму 10000 тенге
Когда пользователь применяет промокод на скидку 10%
Тогда сумма заказа становится 9000 тенгеВо втором варианте нет ни интерфейса, ни лишних деталей. Здесь ясно, какое правило проверяется.
Итог
Большинство проблем BDD связано не с инструментами, а с дисциплиной: забыли обсуждение, увлеклись UI, разрастили набор. В восьмой части, «Внедрение BDD в команде: с чего начать и как оценить результат», разберём, как внедрять подход, не повторяя эти ошибки.
С какими из этих проблем вы сталкивались? Какой антипаттерн оказался самым неожиданным?