特色背景

正如你在上面的示例中所注意到的,我们多次重写相同的步骤:

Given the user is on the login page

这可能非常繁琐,特别是如果我们有多个重复使用的给定步骤。Gherkin 通过为我们提供另一个关键字来为此提供解决方案: 背景:

background 关键字用于在功能中的每个方案之前运行在其下面声明的步骤。除非你是肯定的,否则不要添加后台步骤,这对每个场景都是必要的。与其他关键字一样,背景后面是描述或名称,可以在其下方列出注释。很像功能和场景,背景必须用冒号进行。

Feature: Product Login
    As a user, I would like to be able to use my credentials to successfully 
    login. 
    
    Rules:
    - The user must have a valid username
    - The user must have a valid password
    - The user must have an active subscription 
    - User is locked out after 3 invalid attempts
    - User will get a generic error message following 
      login attempt with invalid credentials 

    Background: The user starts out on the login page
        Given the user is on the login page

    Scenario: The user successfully logs in with valid credentials 
        This scenario tests that a user is able to successfully login
        provided they enter a valid username, valid password, and 
        currently have an active subscription on their account. 

        When the user signs in with "valid" credentials
        Then the user should be logged in

    Scenario: The user attempts to log in with invalid credentials 
        This scenario tests that a user is not able to log in when
        they enter invalid credentials

        When the user signs in with "invalid" credentials
        Then the user should be logged in

    Scenario: The user is locked out after too many failed attempts
        This scenario validates that the user is locked out
        of their account after failing three consecutive 
        attempts to log in

        When the user fails to log in 3 times
        Then the user should be locked out of their account