pytestpytest-bdd

Step definition not found error - for the Given step only -- pytest-bdd


Why is the following pytest-bdd code throwing an error:

pytest_bdd.exceptions.StepDefinitionNotFoundError: Step definition is not found: Given "I have an empty shopping cart

Here is the feature file:

Feature: Shopping Cart
              As a customer
              I want to add products to my shopping cart
  So that I can purchase them later

        Scenario Outline: Add products to the shopping cart
            Given I have an empty shopping cart
             When I add <product> to the cart
             Then the cart should contain <product> and shelf number is <shelf_num>

        Examples:
                  | product | shelf_num |
                  | Apples  | 5         |
                  | Bananas | 24        |
                  | Oranges | 11        |

Here is the steps:

scenarios('scenario_example_demo.feature') 

@pytest.fixture
def shopping_cart():
    return []

@given('I have an empty shopping cart')
def empty_shopping_cart(shopping_cart):
    assert len(shopping_cart) == 0

@when(parsers.parse('I add {product} to the cart'))
def add_product(shopping_cart, product):
    shopping_cart.append(product)

@then(parsers.parse('the cart should contain {product} and shelf number is {shelf_num}'))
def verify_cart_contents(shopping_cart, product,shelf_num):
    assert product in shopping_cart and int(shelf_num)>0

Weirdly, when I change the 'Given' to 'When' in the feature file and do same in the steps code, the code works.

code credits: from Medium (Ramkumar R)


Solution

  • The problem is the syntax of your feature file. The Given, When, Then clauses belong to the same scope and should therefore be aligned (e.g. start at the same line position).

    In your case, When and Then are indented relative to Given, so they are seen as sub-items (I don't think this makes actual sense in this case).

    So, the fix is simple to add a space:

    ...
            Scenario Outline: Add products to the shopping cart
                 Given I have an empty shopping cart
                 When I add <product> to the cart
                 Then the cart should contain <product> and shelf number is <shelf_num>
    

    Note that the number of spaces (e.g. the indent) is not important, just the alignment.