Search code examples
python-3.xgherkinpython-behave

Behave, multiple steps with same name


I have two feature files:

delete.feature
new_directory.feature

And two step files:

delete.py 
new_directory.py

Each one of the feature files begins like this:

Background:
  Given 'Workspace has the following structure'

Following the different tables.

When i write in step file decorator:

 @given('Workspace has the following structure') 

How does it know which feature file background belongs? When I run behave for

new_directory.feature

I can see that it runs that step from delete.feature. Is there any way to make difference between those files except from having all unique step names?


Solution

  • The way I've resolved having a shared step is to use a single implementation for the step that works differently depending on the feature that is using the step. Adapted to what you describe, it would be something like:

    @given('Workspace has the following structure') 
    def step_impl(context):
        feature = context.feature
    
        name = os.path.splitext(os.path.basename(feature.filename))[0]
        if name == "delete":
            # do something
            ...
        elif name == "new_directory":
            # do something else
            ...
        else:
            raise Exception("can't determine how to run this step")
    

    The code above is based on checking the base name (minus extension) of the file that contains the feature. You could also check the actual feature name but I consider file names to be more stable than feature names so I prefer to test file names.