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: