有幾種方法可以讓你的 Gherkin 更好。

描述行為

您的情境應該描述系統的預期行為,而不是實作。換句話說,它應該描述什麼,而不是如何

例如,對於驗證情境,您應該撰寫

When "Bob" logs in

而不是

  Given I visit "/login"
  When I enter "Bob" in the "user name" field
    And I enter "tester" in the "password" field
    And I press the "login" button
  Then I should see the "welcome" page

第一個範例,當「Bob」登入時,是一個功能需求。第二個,長得多的範例是一個程序參考。功能需求是功能,但程序屬於實作細節。

這樣,當功能的實作變更時,您只需要變更幕後的流程步驟。行為不必僅僅因為實作變更而變更。事實上,在撰寫功能子句時,一個很好的問題是問自己:「如果實作變更,這個措辭是否需要變更?」。

如果答案是「是」,那麼您應該重新設計它,避免特定於實作的細節。作為額外的好處,因此您的情境將會簡短得多,且更容易追蹤和理解。

考慮更宣告式風格

使情境更易於維護且不易損壞的一種方法是使用宣告式風格。宣告式風格描述應用程式的行為,而不是實作細節。宣告式情境讀起來更像「即時文件」。宣告式風格可協助您專注於客戶獲得的價值,而不是他們將使用的按鍵。

命令式測試傳達細節,在某些情況下,這種測試風格是適當的。另一方面,由於它們與目前 UI 的機制緊密相關,因此它們通常需要更多的工作來維護。每當實作變更時,也需要更新測試。

以下是命令式風格的功能範例

Feature: Subscribers see different articles based on their subscription level 

Scenario: Free subscribers see only the free articles
  Given users with a free subscription can access "FreeArticle1" but not "PaidArticle1" 
  When I type "freeFrieda@example.com" in the email field
  And I type "validPassword123" in the password field
  And I press the "Submit" button
  Then I see "FreeArticle1" on the home page
  And I do not see "PaidArticle1" on the home page

Scenario: Subscriber with a paid subscription can access "FreeArticle1" and "PaidArticle1"
  Given I am on the login page
  When I type "paidPattya@example.com" in the email field
  And I type "validPassword123" in the password field
  And I press the "Submit" button
  Then I see "FreeArticle1" and "PaidArticle1" on the home page  

每個步驟都是精確的指令。輸入和預期結果都已準確指定。但是很容易想像對應用程式的變更需要變更這些測試。免費與付費訂閱的可用選項可能會變更。甚至登入的方式也可能會變更。如果未來使用者使用語音介面或指紋登入呢?

更宣告式的風格隱藏了應用程式功能如何實作的細節。

Feature: Subscribers see different articles based on their subscription level
 
Scenario: Free subscribers see only the free articles
  Given Free Frieda has a free subscription
  When Free Frieda logs in with her valid credentials
  Then she sees a Free article

Scenario: Subscriber with a paid subscription can access both free and paid articles
  Given Paid Patty has a basic-level paid subscription
  When Paid Patty logs in with her valid credentials
  Then she sees a Free article and a Paid article

使用宣告式風格,每個步驟都會傳達一個概念,但不會指定確切的值。使用者如何與系統互動的細節,例如哪些特定文章是免費或付費的,以及不同測試使用者的訂閱級別,都會在步驟定義中指定(與系統互動的自動化程式碼)。訂閱方案未來可能會變更。企業可以變更免費和付費方案的訂閱者可以使用哪些內容,而無需變更此情境以及使用相同步驟定義的其他情境。如果稍後新增另一個訂閱級別,則很容易為其新增情境。透過避免使用「按一下按鈕」之類的暗示實作的術語,情境更能適應 UI 的實作細節。即使稍後實作變更,情境的意圖仍保持不變。此外,情境中包含過多的實作細節,會使其更難理解其說明的預期行為。

您可以協助我們改進此文件。編輯此頁面