cucumber学习笔记5

上一篇 / 下一篇  2013-08-26 15:13:59

Transform. captured arguments:
 
When Cucumber matches a step definition, it checks for any transforms that match each argument. When an argument matches a transform, Cucumber passes the captured string to the transform’s block, and the result of running the block is what’s then yielded to the step definition.

Step-->Step Definition Regular Expression-->captured argument-->
transform-->Step Definition Ruby Code Block

Given /^I have deposited \$(\d+) in my account$/ do |amount|
my_account = Account.new
my_account.deposit(amount.to_i)
my_account.balance.should eq(amount.to_i),
"Expected the balance to be #{amount} but it was #{my_account.balance}"
end

we have duplication of "amount.to_i" in the Scenario,
Let's remove the duplication:

---->

Transform. /^\d+$/ do |number|
number.to_i
end

Given /^I have deposited \$(\d+) in my account$/ do |amount|
my_account = Account.new
my_account.deposit(amount)
my_account.balance.should eq(amount),
"Expected the balance to be #{amount} but it was #{my_account.balance}"
end


But,the regular expression that we use to capture the number is now duplicated: we have \d+ both in the step definition and in the transform’s definition.Fortunately, Cucumber allows us to define the regular expression once, in the transform, and then reuse it in the step definition,like this:

CAPTURE_A_NUMBER = Transform. /^\$(\d+)$/ do |number|
number.to_i
end

Given /^I have deposited (#{CAPTURE_A_NUMBER}) in my account$/ do |amount|
my_account = Account.new
my_account.deposit(amount)
my_account.balance.should eq(amount),
"Expected the balance to be #{amount} but it was #{my_account.balance}"
end


Creating Custom Helper Methods:
We defined my_account on a module called KnowsMyAccount and then told Cucumber to mix that module into our Worl d by calling Cucumber’s special World method.

module KnowsMyAccount
def my_account
@my_account ||= Account.new
end
end

World(KnowsMyAccount)

In this case, you’ll be extending a World object that Cucumber has created for you. By default, Cucumber creates each World by simply calling Object.new, but you can override this and use a different class if you need to, by passing a block to the World method:

class MySpecialWorld
def some_helper_method
# …
end
end
World{ MySpecialWorld.new }

TAG:

 

评分:0

我来说两句

我的栏目

日历

« 2024-03-23  
     12
3456789
10111213141516
17181920212223
24252627282930
31      

数据统计

  • 访问量: 31458
  • 日志数: 22
  • 建立时间: 2013-08-19
  • 更新时间: 2014-04-01

RSS订阅

Open Toolbar