閱讀668 返回首頁    go 技術社區[雲棲]


《Cucumber:行為驅動開發指南》——2.2 創建一個特性

本節書摘來自異步社區《Cucumber:行為驅動開發指南》一書中的第2章,第2.2節,作者:【英】Matt Wynne , 【挪】Aslak Hellesy著,更多章節內容可以訪問雲棲社區“異步社區”公眾號查看

2.2 創建一個特性

Cucumber測試都歸類為特性(feature)。我們使用這個名字是希望用它描述用戶運行程序時使用的一些特性。首先我們要創建一個目錄,該目錄存放程序文件以及我們即將編寫的特性文件。

$ mkdir calculator
$ cd calculator

我們要讓 Cucumber 引導整個計算器程序的開發過程,於是我們首先在這個空目錄下運行一下cucumber命令:

$ cucumber

You don't have a 'features' directory. Please create one to get started. 
See https://cukes.info/ for more information.

由於我們沒有聲明任何命令行參數,Cucumber會認為我們使用了默認的features文件夾存放測試。這沒什麼問題,隻是目前我們還沒有任何測試。我們遵循這一目錄結構的約定來創建一個features目錄:

$ mkdir features
然後再運行一下Cucumber:

$ cucumber

0 scenarios
0 steps
0m0.000s

每個 Cucumber 測試稱為一個場景(scenario),每個場景都包含一些步驟(step),這些步驟告訴Cucumber具體做什麼。上述的輸出說明Cucumber現在已經能夠正確掃描features目錄了,不過它還沒找到可運行的場景。下麵我們來創建一個場景。

我們的用戶調查顯示,67%的數學運算是加法,因此加法是我們首先要支持的運算。你可以打開自己最喜歡的編輯器,創建一個名為featur``es/adding.feature的文本文件,在其中添加如下內容:

下載first_taste/01/features/adding.feature
Feature: Adding

 Scenario: Add two numbers
  Given the input "2+2"
  When the calculator is run 
  Then the output should be "4"

這個.feature文件包含了計算器程序的第一個場景。我們將上一節的一個實例翻譯成了Cucumber場景,以後我們可以讓計算機一遍又一遍地運行這個場景。或許你已經看到,Cucumber對這個文件的結構實際上是有一些要求的,結構就是這裏的Feature、Scenario、Given、When、Then等關鍵字,其他的所有內容都是文檔。雖然書中這些關鍵字被標粗了(可能你的編輯器也會將它們標亮),但該文件隻是簡單的文本文件。這個結構就叫做Gherkin。

保存文件內容,然後運行cucumber,你應該能看到比上次多了好些輸出:

$ cucumber

Feature: Adding

 Scenario: Add two numbers   # features/adding.feature:3
  Given the input "2+2"    # features/adding.feature:4
  When the calculator is run   # features/adding.feature:5
  Then the output should be "4" # features/adding.feature:6

1 scenario (1 undefined)
3 steps (3 undefined)
0m0.003s

You can implement step definitions for undefined steps with these snippets: 

Given /^the input "([^"]*)"$/ do |arg1|
 pending # express the regexp above with the code you wish you had
end

When /^the calculator is run$/ do
 pending # express the regexp above with the code you wish you had
end

Then /^the output should be "([^"]*)"$/ do |arg1|
 pending # express the regexp above with the code you wish you had
end

If you want snippets in a different programming language,
just make sure a file with the appropriate file extension
exists where cucumber looks for step definitions.

哇,突然來了這麼多輸出!讓我們看看究竟發生了什麼。首先,我們能看到Cucumber找到了我們的特性並嚐試運行它,這一步非常明白,因為Cucumber已經把這個特性的內容照搬到了終端上。你可能還注意到了輸出摘要中原來的0 scenarios已經變成了1 scenario``(undefined),這表示Cucumber已經讀取了我們的特性中的場景但還不知道如何運行它。

其次,Cucumber打印了三段代碼,它們是用Ruby編寫的步驟定義(step definition)樣例代碼,用來告訴Cucumber如何將日常英語描述的步驟翻譯成一係列運行在我們應用程序之上的動作。下一步我們要做的就是將這些代碼片段放入Ruby文件,然後開始豐富這些代碼。

Gherkin特性是麵向業務的,再往下一層是步驟定義,不過在探索這一層之前有必要快速看一看全局圖,以防有人感到困惑。圖2-1可以提醒我們各種元素是如何組織在一起的,我們從包含場景和步驟的特性開始,場景中的步驟會訪問步驟定義,後者將Gherkin特性和我們構建的應用程序連接在一起。

screenshot


圖2-1 Cucumber測試集的主要層次

現在我們將實現一些步驟定義,那樣場景就不再是未定義(undefined)的了。

最後更新:2017-06-06 07:33:54

  上一篇:go  《配置管理最佳實踐》——導讀
  下一篇:go  《Cucumber:行為驅動開發指南》——1.4 Cucumber如何工作