【问题标题】:Can you define instance variables during Cucumber's Given, When, and Then step definitions您能否在 Cucumber 的 Given、When 和 Then 步骤定义期间定义实例变量
【发布时间】:2013-12-13 04:14:23
【问题描述】:

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

您能否在“时间”和“然后”步骤定义期间也定义实例变量 并在后面的 When 和 Then 步骤定义中访问它们?

如果可能的话,定义实例变量是否是一种常见的做法? 何时和然后步骤定义?

谢谢。

【问题讨论】:

    标签: cucumber bdd


    【解决方案1】:

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

    例如,给定特征:

    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 步骤中设置实例变量是否是一种好习惯,这并不比在给定的步骤中进行。理想情况下,您的任何步骤都不会使用实例变量,因为它们会创建步骤耦合。但是,实际上,我在使用实例变量时并没有遇到重大问题。

    【讨论】:

    • 您的回答对我帮助很大。但是,我现在在想:有没有办法检查一步计算的最后一个值?我的意思是,我们可以简单地检查上一步的“last_value”,而不是通过引用一个公共实例变量来“耦合”这些步骤吗?有办法吗?
    • @KeillRandor,我不知道这样做的方法。我没有听说有人这样做,因此可能需要对框架进行一些修改。
    • 好的,我明白了。我通过设置实例变量来做到这一点,所以谢谢!
    猜你喜欢
    • 1970-01-01
    • 2021-09-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多