Search code examples
pythonpython-3.xbddpython-behave

Define a Behave step that works for multiple keywords (e.g. Given, When, and Then)


Is there a way to write a step that works for multiple keywords. Like say my feature is:

Scenario: Something happens after navigating 
  Given I navigate to "/"
    And say some cookie gets set
  When I navigate to "/some-other-page"
  Then something happens because of that cookie

I'm trying to avoid having to define both:

    @given('I navigate to "{uri}"')
    def get(context, uri):
        current_url = BASE_URL + uri
        context.driver.get(current_url)

    @when('I navigate to "{uri}"')
    def get(context, uri):
        current_url = BASE_URL + uri
        context.driver.get(current_url)

If you only define one and try to use it as both you get a raise NotImplementedError(u'STEP: error. With the above example it's not that bad because the step is simple but it seems like it's bad practice to repeat code and you could have the same thing happening with something more complicated, to me it seems like it would make sense if there was like a @all or @any keyword.

Apologies if this has been answered somewhere but it's a hard thing to search for as it's hard to find unique search terms for this type of question


Solution

  • It turns out this can be done using @step. e.g.

    from behave import step
    
    @step('I navigate to "{uri}"')
    def step_impl(context, uri):
         current_url = BASE_URL + uri
         context.driver.get(current_url)
    

    Will work for:

    Scenario: Demo how @step can be used for multiple keywords
        Given I navigate to "/"
        When I navigate to "/"
        Then I navigate to "/"
    

    Note: Figured this out from the ticket which led to this file.