修改黄瓜周围钩子中的过程中的实例变量

发布于 2024-11-06 01:44:53 字数 564 浏览 1 评论 0原文

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

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

使用 Before 钩子在我的 env.rb 中使用 getter,例如

class Person
  def be_happy
    puts "smiling"
  end
end

person = Person.new

Before do
  @person = person
end

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

但如果我想使用 around 钩子,我的理解是它产生一个过程,我可以从中调用步骤中的块,例如,

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

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

When using cucumber, I reference an instance variable used in a step definition e.g.

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

With a getter in my env.rb using the Before hook e.g.

class Person
  def be_happy
    puts "smiling"
  end
end

person = Person.new

Before do
  @person = person
end

All good so far ...

But if I want to use an Around hook instead, my understanding is that it yields a proc from which I can call the block that was in the step e.g.

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

But this fails, as @person is nil. Is this because @person is instantiated when the proc is created, and thus cannot be modified. Is there a way to do this?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

撩人痒 2024-11-13 01:44:53

我想到了两种解决方案

使用世界

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

class Person
  def be_happy
    puts "smiling"
  end
end

World do
  Person.new
end

Around do |scenario, block|
  block.call
end

然后你的步骤 def 应该做一些更像这样的事情:

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

通过这种方法,你在每个场景中都会得到一个新的分支 Person,这可能是一件好事。

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

class Person
  def be_happy
    "smiling"
  end
end

MyPerson = Person.new

Around do |scenario, block|
  block.call
end

使用步骤 def ,如下所示:

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

Two solutions come to mind

Using a World

Try using World, perhaps with something like this in env.rb:

class Person
  def be_happy
    puts "smiling"
  end
end

World do
  Person.new
end

Around do |scenario, block|
  block.call
end

And your step def should then do something more like:

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

With this approach, you get a branch new Person every scenario, which is probably a good thing.

Using a Constant
In the event you don't want a brand new Person for every scenario, just use a constant, perhaps like so:

class Person
  def be_happy
    "smiling"
  end
end

MyPerson = Person.new

Around do |scenario, block|
  block.call
end

with step def like so:

Given /^I have an instance variable in my step$/ do
  MyPerson.be_happy.should eql("smiling")
end
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文