The post has been translated automatically. Original language: Russian
This is the second part of a series about BDD. In the first part, "what is BDD and why it is needed," we have analyzed the basics. In the third, "Gherkin: How to Write Good Scripts," we'll learn how to write down the examples we found.
Many people think that BDD starts with files.feature and special libraries. In fact, it starts earlier: with a conversation. In BDD, this stage is called Discovery, and it is this stage that provides most of the benefits.
The practice of the "three amigos"
A short meeting of the three roles before the start of implementation:
• Business (product manager, analyst, subject area expert): he knows why the function is needed and what rules apply.
• Development: evaluates how it can be implemented and sees the technical limitations.
• Testing: Looks for borderline cases and asks uncomfortable questions.
Roles are more important than people. Sometimes there are more than three "amigos", sometimes one person combines two roles. The main thing is that the views should be different.
A good meeting takes from half an hour to an hour and takes apart one small function. If the discussion drags on, the function is probably too big and should be split up.
Example Mapping
One of the popular techniques for such meetings is called Example Mapping. It was promoted by the authors of the Cucumber tool. It requires colored cards (or their digital equivalent).:
• Yellow: User story or feature that we are discussing.
• Blue: the rules according to which the function works.
• Green: Specific examples illustrating each rule.
• Red: questions that don 't have an answer right now.
Example: promo code in the shopping cart
Function (yellow): the user applies a promo code and gets a discount.
Rule 1 (blue): The promo code gives you a discount as a percentage of the order amount.
• Example: order 10,000 tenge, promo code 10%, total 9,000 tenge.
• Example: an order of 5,000 tenge, a 20% promo code, and a total of 4,000 tenge.
Rule 2 (blue): expired promo code is not applied.
• Example: the validity period expired yesterday, there is no discount, the user sees the message.
Questions (red):
• Is it possible to apply multiple promo codes at the same time?
• Is the promo code valid for products that are already discounted?
How to read the meeting result
• Lots of red cards. The feature is not ready for development yet: we need answers first.
• A lot of blue rules. The function is probably too big. Divide it into several stories.
• There are few green examples. The rules are understood superficially, it is worth adding specifics.
• A good map: the rules are backed up by examples, there are few questions, and they make it clear who will answer and when.
What does such a meeting provide?
The "what if..." questions appear at the discussion stage, not on the demo. The developer comes to the task with a ready set of examples. The tester will not open the function for the first time after the implementation. A business sees how its rules look on specific numbers, and sometimes finds contradictions in them.
Result
Discovery is a cheap way to find misunderstandings: colored flashcards cost much less than the rewritten code. In the third part, "Gherkin: How to write good scripts," we'll look at how to write down the found examples so that the whole team can read them .
Do you have similar discussions before development? What helps you find missing scenarios?
Это вторая часть серии о BDD. В первой части, «что такое BDD и зачем он нужен», мы разобрали основы. В третьей, «Gherkin: как писать хорошие сценарии», научимся записывать найденные примеры.
Многие думают, что BDD начинается с файлов .feature и специальных библиотек. На самом деле он начинается раньше: с разговора. В BDD эту стадию называют Discovery (исследование), и именно она даёт большую часть пользы.
Практика «трёх амиго»
Короткая встреча трёх ролей до начала реализации:
• Бизнес (продукт-менеджер, аналитик, эксперт предметной области): знает, зачем нужна функция и какие правила действуют.
• Разработка: оценивает, как это можно реализовать, и видит технические ограничения.
• Тестирование: ищет пограничные случаи и задаёт неудобные вопросы.
Роли важнее людей. Иногда «амиго» бывает больше трёх, иногда один человек совмещает две роли. Главное, чтобы взгляды были разными.
Хорошая встреча занимает от получаса до часа и разбирает одну небольшую функцию. Если обсуждение затягивается, функция, вероятно, слишком большая и её стоит разделить.
Example Mapping
Одна из популярных техник для таких встреч называется Example Mapping. Её продвигали авторы инструмента Cucumber. Для неё нужны цветные карточки (или их цифровой аналог):
• Жёлтая: пользовательская история или функция, которую обсуждаем.
• Синие: правила, по которым работает функция.
• Зелёные: конкретные примеры, иллюстрирующие каждое правило.
• Красные: вопросы, на которые прямо сейчас нет ответа.
Пример: промокод в корзине
Функция (жёлтая): пользователь применяет промокод и получает скидку.
Правило 1 (синяя): промокод даёт скидку в процентах от суммы заказа.
• Пример: заказ 10 000 тенге, промокод 10%, итог 9 000 тенге.
• Пример: заказ 5 000 тенге, промокод 20%, итог 4 000 тенге.
Правило 2 (синяя): просроченный промокод не применяется.
• Пример: срок действия истёк вчера, скидки нет, пользователь видит сообщение.
Вопросы (красные):
• Можно ли применить несколько промокодов одновременно?
• Действует ли промокод на товары, которые уже со скидкой?
Как читать результат встречи
• Много красных карточек. Функция пока не готова к разработке: сначала нужны ответы.
• Много синих правил. Функция, вероятно, слишком большая. Разделите её на несколько историй.
• Мало зелёных примеров. Правила поняты поверхностно, стоит добавить конкретики.
• Хорошая карта: правила подкреплены примерами, вопросов немного, и по ним понятно, кто и когда ответит.
Что даёт такая встреча
Вопросы «а что если…» появляются на этапе обсуждения, а не на демо. Разработчик приходит к задаче с готовым набором примеров. Тестировщик не откроет функцию впервые уже после реализации. Бизнес видит, как его правила выглядят на конкретных числах, и иногда сам находит в них противоречия.
Итог
Discovery это дешёвый способ найти недопонимание: цветные карточки стоят намного меньше, чем переписанный код. В третьей части, «Gherkin: как писать хорошие сценарии», разберём, как записать найденные примеры так, чтобы их могла читать вся команда.
Проводите ли вы подобные обсуждения перед разработкой? Что помогает вам находить пропущенные сценарии?