Leonardo
Leonardo

Reputation: 1891

Behave step disambiguation/optional step arguments

I'm trying to support the following feature scenario:

Feature: test
  Scenario: Test optional
      Given attacked by samurai
        And attacked by samurai from behind

My steps file is

from behave import step

@step('attacked by {opponent}')
def step_attacked_by(context, opponent):
    print(opponent)

@step('attacked by {opponent} from {direction}')
def step_attacked_by(context, opponent, direction):
    print(opponent)
    print(direction)

I'm getting the error:

behave.step_registry.AmbiguousStep: @step('attacked by {opponent} from {direction}') has already been defined in
  existing step @step('attacked by {opponent}') at steps/test.py:5

I then tried to use optinal arguments:

My feature file:

Feature: test
  Scenario: Test optional
      Given attacked by a samurai

My steps file:

import parse

from behave import step, register_type

@parse.with_pattern(r"a\s+")
def parse_word_a(text):
    """Type converter for "a " (followed by one/more spaces)."""
    return text.strip()

register_type(a_=parse_word_a)

@step('attacked by {:a_?}{opponent}')
def step_attacked_by(context, a_, opponent):
    print(a_)
    print(opponent)

And I'm getting this error:

    raise ValueError('format spec %r not recognised' % type)
ValueError: format spec 'a_?' not recognised

I don't think I really need an optional argument as long as I can disambiguate the steps in the first example.

Upvotes: 1

Views: 1307

Answers (1)

Monica Voinescu
Monica Voinescu

Reputation: 110

While working with Behave, I noticed that the order in which you define the steps in the steps definition file is important.

Try to define your steps starting with the most specific one first:

@step('attacked by {opponent} from {direction}')
def step_attacked_by(context, opponent, direction):
    print(opponent)
    print(direction)

@step('attacked by {opponent}')
def step_attacked_by(context, opponent):
    print(opponent)

Running your test.feature doesn't give me the ambiguity error anymore.

Upvotes: 4

Related Questions