Leon's Blogging

Coding blogging for hackers.

Cucumber

| Comments

BDD 行為驅動開發工具

  • Behavior Driven Development BDD 行為驅動開發工具
  • Cucumber 通過 Gherkin 語言来描述語句

好處

  • 會說話的程式碼
  • 用口語方式寫測試
  • 讓溝通更順暢
  • 使用人類的語言來描述程式行為
  • 明確溝通需求
  • 測試即文件
  • 消除落差
  • 留作紀錄

Usage

描述行為

1
2
3
4
5
6
7
8
9
Feature (功能)             #功能說明, 使用情境
  Scenario(場景,劇本)    #操作方式 特定流程
      Step    (步驟)      #操作步驟
      Given   (假設)      #前情提要, 初始化
      And     (並且)      #更多前情提要
      When    ()        #執行動作
      And     (並且)      #更多動作 
      Then    (那麼)      #預期結果
      And     (並且)      #更多結果

撰寫測試

1
2
3
4
5
6
7
8
9
#features/cucumber.feature
Feature:
  Add two number

  Scenario: Add 1 and 2 should be 3
  Given the first number is 1
  And the second numner is 2
  When calculate two number
  Then result should be 3
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#features/step_definitions/interaction_steps.rb
Given(/^the first number is (\d+)$/) do |num1|
  @num1 = num1.to_i
end

Given(/^the second numner is (\d+)$/) do |num2|
  @num2 = num2.to_i
end

When(/^calculate two number$/) do
  @sum = @num1 + @num2
end

Then(/^result should be (\d+)$/) do |result|
  @sum.should === result.to_i
end
1
2
3
4
5
6
7
8
9
10
11
12
console
Feature:
  Add two number

  Scenario: Add 1 and 2 should be 3 # features/command_options.feature:4
    Given the first number is 1     # features/step_definitions/interaction_steps.rb:1
    And the second numner is 2      # features/step_definitions/interaction_steps.rb:5
    When calculate two number       # features/step_definitions/interaction_steps.rb:9
    Then result should be 3         # features/step_definitions/interaction_steps.rb:13

1 scenario (1 passed)
4 steps (4 passed)

產表工具

cucumber-html-report

測試涵蓋率

Istanbul

參考文件:

Comments