BDD with Python & Behave Tutorial: Making Code and Business “Speak the Same Language”

Python tutorial - IT technology blog
Python tutorial - IT technology blog

Quick Start: Running Your First BDD Scenario in 5 Minutes

Instead of dissecting dry theory, let’s dive straight in. BDD (Behavior-Driven Development) is essentially a way to tell the story of a user’s interaction with software. In the Python ecosystem, Behave is the most powerful tool to bring that vision to life.

Step 1: Install the library

pip install behave

Step 2: Set up a standard directory structure

Behave is quite strict about file structure. You need to organize it as follows so the engine can automatically recognize your scenarios:

my_project/
├── features/
│   ├── steps/
│   │   └── calculator_steps.py
│   └── calculator.feature

Step 3: Write the scenario (.feature file)

Open the calculator.feature file. This is where we use Gherkin—a language that both managers and clients can understand:

Feature: Basic Calculator

  Scenario: Add two integers
    Given I have the number 5
    And I have the number 10
    When I perform the addition
    Then the result should be 15

Step 4: Implement the logic (.py file)

In the steps/calculator_steps.py file, we will define the Python code corresponding to each line above:

from behave import given, when, then

@given('I have the number {num:d}')
def step_given_number(context, num):
    if not hasattr(context, 'numbers'):
        context.numbers = []
    context.numbers.append(num)

@when('I perform the addition')
def step_when_add(context):
    context.result = sum(context.numbers)

@then('the result should be {expected:d}')
def step_then_check(context, expected):
    assert context.result == expected, f"Incorrect result! The calculator returned {context.result}"

Step 5: Run and enjoy

Type the behave command in your terminal. If the screen displays green text with the message “1 scenario passed,” you have officially entered the world of professional Automation Testing.

Why Are Agile Teams “Crazy” About BDD?

Have you ever spent time writing a high-quality Unit Test suite only to have the client look at it and shake their head? That’s because traditional test code is often too dry. BDD was born to bridge this gap by using Gherkin as a communication bridge.

  • Given (Context): Setting up the initial scene, such as sample data or initializing a browser.
  • When (Action): Describing user interactions like clicking a button or calling an API.
  • Then (Result): Verifying if the output matches expectations.

Behave acts as an intelligent mapper. It scans every Gherkin line and finds the corresponding @given, @when, and @then functions. Notably, the context object acts like a “magic bag,” helping you pass data smoothly between steps within the same Scenario without losing track of it.

Advanced Techniques: Don’t Let Test Cases Bloat Unnecessarily

If you need to test 100 data sets, would you copy-paste the scenario 100 times? Don’t do that. Scenario Outline will help you save 80% of your coding effort through its looping mechanism.

Scenario Outline: Check multiple calculations
  Given I have the number <num_1>
  And I have the number <num_2>
  When I perform the addition
  Then the result should be <result>

  Examples: Test Data
    | num_1 | num_2 | result |
    | 1     | 2     | 3      |
    | 10    | 20    | 30     |
    | 99    | 1     | 100    |

Behave will automatically rerun the scenario based on the Examples table. This is extremely effective when you need to handle edge cases without cluttering your feature file.

Managing the Lifecycle with Hooks

When automating web applications, constantly opening and closing browsers can be a drain on system resources. Leverage the environment.py file to take control:

  • before_all: Set up general configurations only once.
  • before_scenario: Prepare a clean environment for each scenario.
  • after_scenario: Clean up, close the browser, or take a screenshot if the test fails.

Real-World Lessons and Best Practices

Writing BDD scenarios is easy, but maintaining them over the lifespan of a project is another story. Here are a few tips I’ve gathered along the way.

1. The Power of Regex and Supporting Tools

Behave allows the use of Regular Expressions (Regex) to capture parameters flexibly. When dealing with complex patterns, you should verify them carefully to avoid incorrect data capture. I often use Toolcraft’s regex tester to quickly check patterns directly in the browser. This saves significant time when debugging Gherkin scenarios.

2. The “Less is More” Rule

Don’t overuse the word And. If a Scenario is 20 lines long, it’s a sign that it’s getting bogged down in technical details. Group them together. Instead of describing every single click, write: “The user completes payment with a Visa card.” This keeps the scenario concise and more business-focused.

3. Divide and Conquer (Modularization)

As the project grows, the steps.py file will become a mess. Proactively split them into modules like auth_steps.py or payment_steps.py. Behave is smart enough to scan the entire steps/ folder, so feel free to organize it in the most manageable way.

4. Don’t Skimp on Assert Messages

On CI/CD systems like Jenkins or GitHub Actions, a clear error log is worth a thousand words. Instead of leaving a generic error, write: “Error: System returned 404 instead of 200 at the login step”. You’ll thank yourself when you have to debug in the middle of the night.

Using BDD is not just about finding bugs. It’s a way to build trust with clients by showing: “I am building exactly what you need.” Good luck applying Behave to your projects!

Share: