這裡將描述幾種反模式。我們也會提供您如何避免這些反模式的提示!

與功能耦合的步驟定義

與功能耦合的步驟定義是指**無法**跨功能或情境重複使用的步驟定義。

這可能會導致步驟定義爆炸性增加、程式碼重複和高維護成本。

範例

一個虛擬的履歷應用程式可以有以下的功能和步驟定義檔

features/
+--edit_work_experience.feature
+--edit_languages.feature
+--edit_education.feature
+--steps/
   +--edit_work_experience_steps.java
   +--edit_languages_steps.java
   +--edit_education_steps.java
features/
+--edit_work_experience.feature
+--edit_languages.feature
+--edit_education.feature
+--steps/
   +--edit_work_experience_steps.kt
   +--edit_languages_steps.kt
   +--edit_education_steps.kt
features/
+--edit_work_experience.feature
+--edit_languages.feature
+--edit_education.feature
+--steps/
   +--edit_work_experience_steps.js
   +--edit_languages_steps.js
   +--edit_education_steps.js
features/
+--edit_work_experience.feature
+--edit_languages.feature
+--edit_education.feature
+--steps/
   +--edit_work_experience_steps.rb
   +--edit_languages_steps.rb
   +--edit_education_steps.rb

edit_work_experience.feature 可能有以下情境

Scenario: add description
  Given I have a CV and I'm on the edit description page
  And I fill in "Description" with "Cucumber BDD tool"
  When I press "Save"
  Then I should see "Cucumber BDD tool" under "Descriptions"

可以像這樣實作

    @Given("I have a CV and I'm on the edit description page")
    public void I_have_a_CV_and_Im_on_the_edit_description_page() {
        Employee employee = new Employee("Sally");
        employee.createCV();
    }
@Given("I have a CV and I'm on the edit description page")
fun I_have_a_CV_and_Im_on_the_edit_description_page() {
    val employee = Employee("Sally")
    employee.createCV()
}
var { Given } = require('cucumber');

Given(/^I have a CV and I'm on the edit description page$/, function () {
  this.employee = new Employee('Sally');
  this.employee.createCV();
});
Given /I have a CV and I'm on the edit description page/ do
  @employee = Employee.create!(name: 'Sally')
  @employee.create_cv
  visits("/employees/#{@employee.id}/descriptions/new")
end

如何解耦步驟和步驟定義

  • 依領域概念組織您的步驟。

  • 對您的步驟和步驟定義檔使用與領域相關的名稱(而不是與功能或情境相關的名稱)。

連接步驟

來自線上 Merriam-Webster 字典

連·接詞:一種不屈折的語言形式,將句子、子句、片語或單字連接在一起。

請勿使用組合一堆不同事物的步驟。這會使步驟過於專門,且難以重複使用。Cucumber 內建支援連接詞 (And, But) 是有原因的!

範例

Given I have shades and a brand new Mustang

如何拆分連接步驟

Given I have shades
And I have a brand new Mustang

支援連接步驟

有時您可能想要將數個步驟合併為一個,以使您的情境更易於閱讀。例如,如果您需要在 Given 狀態中設定數個前提條件。

實現組合和重複使用的最佳方法是使用程式設計語言的功能。如果您想要將數個動作合併為一個步驟,請提取個別(輔助)方法,並從您的步驟定義中呼叫這些方法。

您希望盡可能保持步驟的原子性。

更多資訊

如需有關反模式的更多資訊,請參閱Cucumber 反模式 (部落格)

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