这个 例子)。
首先编写feature ,并保存为feature/addition.feature文件:
Feature: Addition
In order to avoid silly mistakes
As a math idiot
I want to be told the sum of two numbers
Scenario Outline: Add two numbers
Given I have entered <input_1> into the calculator
And I have entered <input_2> into the calculator
When I press <button>
Then the result should be <output> on the screen
Examples:
| input_1 | input_2 | button | output |
| 20 | 30 | add | 50 |
然后用Ruby语言定义scenario中的每个步骤 ,并保存为features/step_definitions/addition.rb文件:
- Given /I have entered (/d+) into the calculator/ do |n|
- @calc = Calculator.new
- @calc.push n.to_i
- end
- When /I press (/w+)/ do |op|
- @result = @calc.send op
- end
- Then /the result should be (.*) on the screen/ do |result|
- @result.should == result.to_f
- end
最后编写相应代码 :
- class Calculator
- def push(n)
- @args ||= []
- @args << n
- end
- def add
- @args.inject(0){|n,sum| sum+=n}
- end
- end
并进行测试 :
cucumber feature/addition.feature
如果得到类似于以下的结果,则表明代码无误:
1 scenario (1 passed)
4 steps (4 passed)
0m0.009s
否则,会得到红色提示,则需要修改相应代码。