开发者

Modifying instance variable in a proc in cucumber Around hook

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 w开发者_C百科ay to do this?


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
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜