gpt4 book ai didi

ruby - 在 cucumber Around hook 中修改 proc 中的实例变量

转载 作者:太空宇宙 更新时间:2023-11-03 16:57:38 25 4
gpt4 key购买 nike

使用 Cucumber 时,我引用了步骤定义中使用的实例变量,例如

Given /^I have an instance variable in my step$/ do
@person.should_not be_nil
end

使用 Before 钩子(Hook)在我的 env.rb 中使用 setter/getter ,例如

class Person
def be_happy
puts "smiling"
end
end

person = Person.new

Before do
@person = person
end

到目前为止一切都很好......

但是如果我想改用 Around 钩子(Hook),我的理解是它会产生一个过程,我可以从中调用步骤中的 block ,例如

Around do |scenario, block|
@person = person
block.call
end

但这失败了,因为@person 是 nil。这是因为@person 在创建过程时被实例化,因此无法修改。有办法做到这一点吗?

最佳答案

想到了两种解决方案

使用世界

尝试使用 World ,也许在 env.rb 中有这样的东西:

class Person
def be_happy
puts "smiling"
end
end

World do
Person.new
end

Around do |scenario, block|
block.call
end

然后你的 step def 应该做更像的事情:

Given /^I have an instance variable in my step$/ do
be_happy.should eql("smiling")
end

通过这种方法,您可以在每个场景中获得一个分支 new Person,这可能是一件好事。

使用常量如果您不想为每个场景都使用一个全新的 Person,只需使用一个常量,也许像这样:

class Person
def be_happy
"smiling"
end
end

MyPerson = Person.new

Around do |scenario, block|
block.call
end

像这样定义步骤:

Given /^I have an instance variable in my step$/ do
MyPerson.be_happy.should eql("smiling")
end

关于ruby - 在 cucumber Around hook 中修改 proc 中的实例变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5925273/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com