Tutorial 8: Execute Other Steps in a Step

Goal

Reuse a sequence of existing steps as a step-macro.

In some case, you want to replace a number of steps in a scenario by one simple macro step (macro functionality). To avoid code duplication in the test automation layer, the BDD framework normally provides a functionality to easily call these steps from within a step defintion.

Write the Feature Test

# file:features/tutorial08_step_executes_steps.feature
Feature: Step executes other Steps (tutorial08)

   Scenario: Step by Step
     Given I start a new game
     When  I press the big red button
      And  I duck
     Then  I reach the next level

   Scenario: Execute multiple Steps in middle Step
     Given I start a new game
     When  I do the same thing as before
     Then  I reach the next level

Provide the Test Automation

# file:features/steps/step_tutorial08.py
# ----------------------------------------------------------------------------
# STEPS:
# ----------------------------------------------------------------------------
from behave   import given, when, then
from hamcrest import assert_that, greater_than

@given('I start a new game')
def step_impl(context):
    context.duck_count = 0
    context.red_button_pressed = 0

@when('I press the big red button')
def step_impl(context):
    context.red_button_pressed += 1

@when('I duck')
def step_impl(context):
    context.duck_count += 1

@when('I do the same thing as before')
def step_impl(context):
    context.execute_steps(u"""
        when I press the big {button_color} button
         and I duck
    """.format(button_color="red"))

@then('I reach the next level')
def step_impl(context):
    assert_that(context.duck_count, greater_than(0))
    assert_that(context.red_button_pressed, greater_than(0))

Run the Feature Test

When you run the feature file from above:

$ behave ../features/tutorial08_step_executes_steps.feature
Feature: Step executes other Steps (tutorial08)   # ../features/tutorial08_step_executes_steps.feature:1

  Scenario: Step by Step            # ../features/tutorial08_step_executes_steps.feature:3
    Given I start a new game        # ../features/steps/step_tutorial08.py:26
    When I press the big red button # ../features/steps/step_tutorial08.py:31
    And I duck                      # ../features/steps/step_tutorial08.py:35
    Then I reach the next level     # ../features/steps/step_tutorial08.py:46

  Scenario: Execute multiple Steps in middle Step  # ../features/tutorial08_step_executes_steps.feature:9
    Given I start a new game                       # ../features/steps/step_tutorial08.py:26
    When I do the same thing as before             # ../features/steps/step_tutorial08.py:39
    Then I reach the next level                    # ../features/steps/step_tutorial08.py:46

1 feature passed, 0 failed, 0 skipped
2 scenarios passed, 0 failed, 0 skipped
7 steps passed, 0 failed, 0 skipped, 0 undefined
Took 0m0.001s