AUTOMATION FRAMEWORKS

Writing Step Definitions That Stay Reusable in the AI Era

Step definitions are where BDD either pays off or falls apart. I've seen teams write clear Gherkin that stakeholders actually read, then bury it under step functions so tightly coupled to one feature file that they can never be reused. Eventually the suite has a huge pile of steps, many doing nearly the same thing, and nobody wants to touch them.

The cause is writing steps as if every scenario is an island. Reusable steps need a different instinct: you're building a small, composable vocabulary for the suite, not a one-off script with a decorator on it. That changes how you phrase step text, how you parameterise it, where shared state lives and how you organise the files.

Coding agents make this more pressing. Copilot or another agent can implement a step in seconds, which is great, but an agent that doesn't find the existing step will write a new one with slightly different wording. Duplication that used to take a long time to build up now happens in a single PR. In this article I'll cover the Behave patterns I use to keep steps reusable, and how I set up the suite so agents reuse the vocabulary instead of growing a second one.

Build an API Automation Framework With Node.js

Learn Node.js, Cucumber, GitHub Copilot, APIs, CI/CD, and modern automation by building a complete framework.

Learn more

Parameterise what varies, keep the intent words fixed

Hard-coding values into step text is the quickest way to kill reuse. Given the user sends a GET request to /api/v1/products can only ever test one endpoint. Parameterise it:

# features/steps/api_steps.py
from behave import when, then


@when('the client sends a "{method}" request to "{endpoint}"')
def step_send_request(context, method, endpoint):
    context.response = context.session.request(
        method.upper(), f"{context.base_url}{endpoint}", timeout=10)


@then("the response status code is {status_code:d}")
def step_check_status(context, status_code):
    actual = context.response.status_code
    assert actual == status_code, (
        f"Expected {status_code}, got {actual}: {context.response.text}")

The quotes around the values aren't just style. They give the parser clear boundaries, which matters as soon as you have a longer step that starts with the same words. And {status_code:d} converts to an integer for you.

Remember that the decorator type matters in Behave. A step registered with @given matches Given lines (and And lines following them), not When lines. If you genuinely want one step usable under any keyword, use @step, but most of the time the keyword carries meaning and should stay.

The opposite mistake is over-parameterising. Given {actor} performs {action} on {resource} with {payload} is reusable in theory and unreadable in a feature file. Parameterise the values that change between scenarios; keep the words that state intent.

When a step needs several fields, use a table rather than a long list of parameters:

When the client sends a "POST" request to "/api/v1/orders" with this body:
  | field    | value     |
  | product  | widget-42 |
  | quantity | 3         |
@when('the client sends a "{method}" request to "{endpoint}" with this body:')
def step_send_with_table(context, method, endpoint):
    payload = {row["field"]: row["value"] for row in context.table}
    context.response = context.session.request(
        method.upper(), f"{context.base_url}{endpoint}", json=payload, timeout=10)

The trailing colon is part of the step text, so it has to be in the decorator too. Note that table values arrive as strings; convert them in the step if the API expects numbers.

Give context a contract instead of a junk drawer

Behave's context is the right place to share state within a scenario, and the place reuse goes to die if you're careless. I've inherited suites where steps set ad-hoc attributes like context.the_thing and context.temp_user_id that other steps silently depend on. Reuse one of those steps elsewhere and you find out the hard way that it needed four others to run first.

I treat context like an interface and declare what steps can rely on in environment.py:

# features/environment.py
import requests


def before_all(context):
    context.base_url = context.config.userdata.get("base_url", "http://localhost:8000")


def before_scenario(context, scenario):
    context.session = requests.Session()
    context.session.headers["Content-Type"] = "application/json"
    context.response = None
    context.auth_token = None


def after_scenario(context, scenario):
    context.session.close()

The base URL comes from behave -D base_url=..., so the same suite runs against any environment. Every step now knows context.response and context.session exist and what they mean, and a step that runs too early gets a clear None instead of a confusing AttributeError.

Keep steps thin. Put real logic, such as fetching a token, in a plain helper module and call it from the step:

# features/steps/auth_steps.py
from behave import given
from support.auth import fetch_auth_token


@given("the client is authenticated as {role}")
def step_authenticate(context, role):
    context.auth_token = fetch_auth_token(context.base_url, role)
    context.session.headers["Authorization"] = f"Bearer {context.auth_token}"

The helper can be unit-tested on its own, and the step only touches well-known context attributes. More on sharing state safely in sharing test data across a Behave suite safely.

Organise step files so steps get found

Behave loads every module in steps/, so any step is technically available everywhere. But "available" isn't "reused". When steps are organised by the feature they were first written for, people write new ones because searching is too much effort. I group by what the step interacts with:

  • api_steps.py: sending requests, checking status and headers
  • auth_steps.py: authentication and permissions
  • schema_steps.py: response structure, such as Then the response matches the "{schema_name}" schema
  • data_steps.py: test data setup and teardown

Feature-specific files like orders_steps.py are fine, but they should be thin. If one starts sending requests itself, that logic belongs in api_steps.py with a parameter. Schema steps are among the most reusable in an API suite; see validating API response schemas automatically for the validation side.

Help agents reuse the vocabulary

Before anyone, human or agent, writes a new step, they should see the existing ones. Behave can print them: behave --steps-catalog lists every registered step definition. I give that list to the agent with the task, or tell it to run the command first. Then the rules go in .github/copilot-instructions.md or your agent's equivalent:

## Behave steps
- Run `behave --steps-catalog` before adding a step. Reuse existing wording where it fits,
  even if that means rewording the new scenario line.
- New steps go in the file for what they touch (api_, auth_, schema_, data_steps.py).
- Steps stay thin: logic goes in features/support/, not in the step body.
- Only use context attributes declared in features/environment.py.

Behave catches some collisions for you: when a step definition is registered whose text an already-loaded pattern would match, it raises an AmbiguousStep error as the steps load. Whether that fires depends on load order, so don't rely on it. Near-duplicates with different wording don't trigger it, though, so I check agent PRs for new step decorators and compare them against the catalogue. A cheap CI check that runs behave --dry-run also catches scenario lines that no step matches, which is what happens when an agent writes Gherkin without implementing it.

A clean vocabulary also makes agents better at the job. When the steps follow a consistent pattern, an agent writing a new scenario can compose it from existing steps, and the only new code is the genuinely new behaviour. I go through that prompting workflow in prompting an AI assistant to write Behave step definitions.

A vocabulary that grows on purpose

The goal is a set of steps that grows deliberately, that anyone on the team can find and reuse, and that an agent extends rather than duplicates. Parameterise what varies, give context a contract, organise by concern, and make the catalogue the first thing every author sees. If you want to build a Behave or Cucumber suite like this with VS Code and GitHub Copilot, my API testing courses cover it end to end.