Behave - 背景


添加背景以具有一组步骤。它接近于一个场景。我们可以通过背景为多个场景添加上下文。它在功能的每个场景之前运行,但在 before 挂钩执行后执行。

后台一般用于执行登录场景或者数据库连接等前置条件。

可以添加背景描述以提高人类可读性。它只能在功能文件中出现一次,并且必须在场景或场景大纲之前声明。

不应使用背景来创建复杂状态(仅当无法避免时)。这一部分应该简短而真实。此外,我们应该避免在一个特性文件中包含大量场景。

带背景的特征文件

标题为付款流程的功能的背景功能文件如下 -

Feature − Payment Process
   Background:
      Given launch application
      Then Input credentials
   Scenario − Credit card transaction
      Given user is on credit card payment screen
      Then user should be able to complete credit card payment
   Scenario − Debit card transaction
      Given user is on debit card payment screen
      Then user should be able to complete debit card payment

对应步骤实施文件

该文件如下 -

from behave import *
@given('launch application')
def launch_application(context):
   print('launch application')
@then('Input credentials')
def input_credentials(context):
   print('Input credentials')
@given('user is on credit card payment screen')
def credit_card_pay(context):
   print('User is on credit card payment screen')
@then('user should be able to complete credit card payment')
def credit_card_pay_comp(context):
   print('user should be able to complete credit card pay')
@given('user is on debit card payment screen')
def debit_card_pay(context):
   print('User is on debit card payment screen')
@then('user should be able to complete debit card payment')
def debit_card_pay_comp(context):
   print('user should be able to complete debit card payment')

输出

下面提到了运行功能文件后获得的输出,这里使用的命令是behave --no-capture -f plain

带背景的特征文件

连续输出如下 -

背景

输出显示后台步骤(给定启动应用程序然后输入凭据)在每个场景之前运行两次。