Skillversitas

Multi-Method Steps

A step function is not limited to a single pattern. By stacking several @step decorators on one function you register the same implementation for multiple step texts. This is the multi-method approach: one body of code, several entry points. It removes duplication when steps differ only in wording.

Stacking Step Decorators

Scenario: Inventory
  Given I have 5 cucumbers
  Given I have 3 apples
  When I eat 2 cucumbers
  Then I have 3 cucumbers left
from behave import step

@step("I have {num} cucumbers")
@step("I have {num} apples")
def step_impl(context, num):
    # one implementation serves both step texts
    context.total_fruit = context.total_fruit + int(num)

The decorators are applied bottom-up, so the function ends up registered for both patterns. Behave looks the step up by the exact pattern that matched, and both lookups resolve to the same function object.

When Stacking Helps

Stacking is ideal when the behavior is truly identical for several wordings, for example a synonym the business team insists on keeping. If the behavior differs per pattern, do not stack; write separate functions or, better, a single pattern with an enumeration so the function can inspect the captured word:

from behave import step

@step("I have {num} {cucumbers|apples}")
def step_impl(context, num, fruit):
    context.stock[fruit] = context.stock.get(fruit, 0) + int(num)

Keeping Step Names Unique

Regardless of how many patterns a function carries, behave still requires that no two different functions claim the same pattern. If you see a "step is already registered" warning, you have two definitions for one pattern; consolidate them into a single multi-method step.

Summary

Multi-method steps let one function serve several step patterns via stacked decorators. Use them when the behavior is identical; otherwise prefer a single pattern with an enumeration so the function can inspect the captured word.