BDD Behave – How to pass step parameter or table into sub step

In this post, We will see how to pass a parameter from a step in feature file into a sub step in step definition.

  1. Step parameter is a String

Feature file:
Given I am have free time
When The book store is open
And I bought “The beautiful mind” in book store

@when(‘I bought “{book_name}” in book store’)
def step_impl(context, book_name):
context.execute_steps(u”””
when I get the book “{}” on the shelf
and I pay it at the counter
“””.format(book_name))

As you see, we can simply use {} and format to pass the value of book_name from feature file into sub step I get the book “{}” on the shelf.

Next let’s see what if the data is a table, how to pass a table into sub step.

2. Step parameter is a table

in Step definition, the table in feature file can be accessed by context.table.

Now, we need to pass the context.table into sub step.

the table in feature file look like:

|name                         |quantity|
|The beautiful Mind|2             |

Let’s turn it to a string which including the special character “\n” to seperate the heading and table rows. It will be like this :

‘|name|quantity|\n|The beautiful Mind|2|’

Below is the function to help you convert a table to string:

def table_to_str(table):
    result = ''
    if table.headings:
        result = '|'
    for heading in table.headings:
        result += heading + '|'
    result += '\n'
    for row in table.rows:
        if row.cells:
            result += '|'
        for cell in row.cells:
            result += cell + '|'
        result += '\n'
    return result

Feature file:
Scenario 1: buy 2 books of The beautiful mind
Given I am have free time
When The book store is open
And I bought some books in book store as below
| book name | quantity |
| The beautiful mind | 2 |

Scenario 2: buy 3 books of The Mind Map
Given I am have free time
When The book store is open
And I bought some books in book store as below
| book name | quantity |
| The Mind Map | 3 |

@when(‘I bought some books in book store as below’)
def step_impl(context):
context.execute_steps(u”””
when I get some books on the shelf as below
{table}
and I pay them at the counter
“””.format(table=step_utils.table_to_str(context.table)))

Leave a comment