特色背景

正如你在上面的示例中所注意到的,我們多次重寫相同的步驟:

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