如何使用 behave context.table 和键值 table?

How to use behave context.table with key value table?

我发现当 BDD 中描述的 table 具有 header 时,可以从 Behave 访问来自 context.table 的数据。例如:

Scenario: Add new Expense
  Given the user fill out the required fields
    | item | name  | amount |
    | Wine | Julie | 30.00  |

要访问此代码,只需:

for row in context.table:
  context.page.fill_item(row['item'])
  context.page.fill_name(row['name'])
  context.page.fill_amount(row['amount'])

效果很好,而且非常干净,但是,当我有大量输入数据行时,我必须重构代码。例如:

Given I am on registration page
When I fill "test@test.com" for email address
And I fill "test" for password
And I fill "Didier" for first name 
And I fill "Dubois" for last name
And I fill "946132795" for phone number
And I fill "456456456" for mobile phon
And I fill "Company name" for company name
And I fill "Avenue Victor Hugo 1" for address
And I fill "97123" for postal code
And I fill "Lyon" for city
And I select "France" country
...
15 more lines for filling the form

如何在行为中使用以下 table:

|first name | didier |
|last name  | Dubois |
|phone| 4564564564   |
So on ...

我的步骤定义是什么样的?

要使用垂直 table 而不是水平 table,您需要将每一行作为其自己的字段进行处理。 table 还需要 header 行:

When I fill in the registration form with:
    | Field      | Value  |
    | first name | Didier |
    | last name  | Dubois |
    | country    | France |
    | ...        | ...    |

在您的步骤定义中,遍历 table 行并在您的 selenium 页面模型上调用一个方法:

for row in context.table
  context.page.fill_field(row['Field'], row['Value'])

Selenium页面模型方法需要根据字段名做一些事情:

def fill_field(self, field, value)
  if field == 'first name':
    self.first_name.send_keys(value)
  elif field == 'last name':
    self.last_name.send_keys(value)
  elif field == 'country':
    # should be instance of SelectElement
    self.country.select_by_text(value)
  elif
    ...
  else:
    raise NameError(f'Field {field} is not valid')