【发布时间】:2013-12-13 04:14:23
【问题描述】:
我知道使用 Cucumber,您可以在给定步骤定义期间定义实例变量。
此实例变量成为World 范围的一部分。
然后你可以在When和Then的步骤定义中访问这个实例变量。
您能否在“时间”和“然后”步骤定义期间也定义实例变量 并在后面的 When 和 Then 步骤定义中访问它们?
如果可能的话,定义实例变量是否是一种常见的做法? 何时和然后步骤定义?
谢谢。
【问题讨论】:
我知道使用 Cucumber,您可以在给定步骤定义期间定义实例变量。
此实例变量成为World 范围的一部分。
然后你可以在When和Then的步骤定义中访问这个实例变量。
您能否在“时间”和“然后”步骤定义期间也定义实例变量 并在后面的 When 和 Then 步骤定义中访问它们?
如果可能的话,定义实例变量是否是一种常见的做法? 何时和然后步骤定义?
谢谢。
【问题讨论】:
是的,您可以在任何步骤类型中设置实例变量。
例如,给定特征:
Feature: Instance variables
Scenario: Set instance variables during all steps
Given a given step sets the instance variable to "1"
Then the instance variable should be "1"
When a when step sets the instance variable to "2"
Then the instance variable should be "2"
Then a then step sets the instance variable to "3"
Then the instance variable should be "3"
以及步骤定义:
Given /a given step sets the instance variable to "(.*)"/ do |value|
@your_variable = value
end
When /a when step sets the instance variable to "(.*)"/ do |value|
@your_variable = value
end
Then /a then step sets the instance variable to "(.*)"/ do |value|
@your_variable = value
end
Then /the instance variable should be "(.*)"/ do |value|
@your_variable.should == value
end
您将看到场景通过,这意味着 when 和 then 步骤已成功设置实例变量。
事实上,Given、When 和 Then 只是彼此的别名。仅仅因为您将步骤定义定义为“Given”,它仍然可以称为“When”或“Then”。例如,如果使用的步骤定义为:
Then /a (\w+) step sets the instance variable to "(.*)"/ do |type, value|
@your_variable = value
end
Then /the instance variable should be "(.*)"/ do |value|
@your_variable.should == value
end
请注意,场景中的“Given”和“When”可以使用第一个“Then”步骤定义。
至于在 when 和 then 步骤中设置实例变量是否是一种好习惯,这并不比在给定的步骤中进行。理想情况下,您的任何步骤都不会使用实例变量,因为它们会创建步骤耦合。但是,实际上,我在使用实例变量时并没有遇到重大问题。
【讨论】: