这是一个简单的问题。我有 Cucumber 步骤,例如:
Given /We have the test environment/ do
@user = # Create User model instance
@post = # Create Post model instance
# etc...
end
在 Then 这一步我使用了我自己的类,它们简化了测试过程:
Then /all should be fine/ do
# MyValidatorClass has been defined somwhere in features/support dir
validator = MyValidatorClass.new
validator.valid?.should be_true
end
在 MyValidatorClass 实例内部,我处理了上述实例变量@user、@post 等。
从 MyValidatorClass 类实例访问 Cucumber 变量的最佳和最简单的方法是什么?
class MyValidatorClass
def valid?
@post
@user
end
end
现在我已经手动将所有参数传递给 MyValidatorClass 实例:
validator = MyValidatorClass.new @user, @post
但是我觉得这个目的不好。 我需要更透明的东西,因为我们使用的是 Ruby,这就是为什么!
执行此操作的最佳方法是什么?
最佳答案
World 中定义的实例变量scope 仅在 World 内部可用。步骤定义属于世界。您应该通过 World{MyValdatorClass.new}
将 MyValdatorClass
放入 World 中。在此之后,先前在此场景的 stepdef 中定义的实例变量将在此类和同一场景中的其他步骤定义中变得可用。
与您的问题有关的其他一些想法:
如果你有一个步骤Given we have the test environment
,那么:
- 您将在所有功能中复制它
- 您的专题变得越来越长,阅读起来也越来越不愉快,因为那些对于当前专题的阅读细节来说是不必要的
- 设置不需要的环境细节需要一些时间
创建实例的更简单方法是添加将为您创建它们的辅助方法:
module InstanceCreator
def user
@user ||= # Create user instance in World
end
#etc
end
World(InstanceCreator)
然后您只需在需要时使用该用户(不带任何 @ 或 @@)。
如果除了创建实例之外还需要其他东西,请使用 hooks
您的场景应该是自然阅读。您不应该用让自动化层正常工作所需的步骤来破坏它们。
最好让正则表达式从 ^ 开始并以 $ 结束。没有它,步骤定义就变得太灵活了。您的第一步定义也将匹配 Given We have the test environment with some specifics
。
关于ruby - 从步骤中的嵌套类访问 Cucumbers 实例变量的最佳方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11287858/