您可以在Cucumber的Given,When和Then步骤定义期间定义实例变量

Zac*_* Xu 5 bdd cucumber

我知道使用Cucumber,您可以在给定步骤定义期间定义实例变量.此实例变量成为World范围的一部分.然后,您可以在When和Then的步骤定义期间访问此实例变量.

您是否可以在When和Then步骤定义期间定义实例变量,并在稍后的When和Then步骤定义中访问它们?

如果可能,在When和Then步骤定义期间定义实例变量是否常见?

谢谢.

Jus*_* Ko 6

是的,您可以在任何步骤类型中设置实例变量.

例如,鉴于该功能:

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"
Run Code Online (Sandbox Code Playgroud)

步骤定义:

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
Run Code Online (Sandbox Code Playgroud)

您将看到场景通过,这意味着when和then步骤成功设置了实例变量.

实际上,Given,When和Then只是彼此的别名.仅仅因为您将步骤定义定义为"给定",它仍然可以被称为"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
Run Code Online (Sandbox Code Playgroud)

请注意,第一个"Then"步骤定义可以由场景中的"Given"和"When"使用.

至于在时间和步骤中设置实例变量是否是一种好的做法,它并不比在给定步骤中执行它更糟糕.理想情况下,您的步骤都不会使用实例变量,因为它们会创建步进耦合.但是,实际上,我没有通过使用实例变量遇到重大问题.