本文介绍了rspec模拟:在其中“期望"验证期望方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用rspec的模拟来设置期望值,我可以在应该"方法中验证该期望值...但是我不知道该怎么做...在我调用.should_receive方法时模拟,它会在before:all方法退出后立即验证预期的调用.

I'm trying to use rspec's mocking to setup expectations that I can verify in the it "should" methods... but I don't know how to do this... when i call the .should_receive methods on the mock, it verifies the expected call as soon as the before :all method exits.

这是一个小例子:

describe Foo, "when doing something" do
 before :all do
  Bar.should_recieve(:baz)
  foo = Foo.new
  foo.create_a_Bar_and_call_baz
 end

 it "should call the bar method" do
  # ??? what do i do here?
 end
end

我该如何在应"方法中验证预期的通话?我需要使用mocha或其他模拟框架代替rspec吗?或???

How can i verify the expected call in the 'it "should"' method? do i need to use mocha or another mocking framework instead of rspec's? or ???

推荐答案

我将对此再作一番抨击,因为从最初的答案和回答中可以很明显地看出,您要尝试的内容有些混乱完成.让我知道这是否更接近您想要做的事情.

I'm going to take another whack at this, because it's clear from the initial set of answers and responses that there was some confusion about what you are trying to accomplish. Let me know if this is closer to what you are trying to do.

describe Foo, "when frobbed" do
  before :all do
    @it = Foo.new

    # Making @bar a null object tells it to ignore methods we haven't
    # explicitly stubbed or set expectations on
    @bar = stub("A Bar").as_null_object
    Bar.stub!(:new).and_return(@bar)
  end

  after :each do
    @it.frob!
  end

  it "should zap a Bar" do
    @bar.should_receive(:zap!)
  end

  it "should also frotz the Bar" do
    @bar.should_receive(:frotz!)
  end
end

顺便说一句,尽管它可以工作,但我不是Bar.stub!(:new)模式的忠实拥护者.我通常更喜欢通过可选参数传递协作者,例如@it.frob!(@bar).如果未提供明确的参数(例如,在生产代码中),则可以默认为协作者:def frob!(bar=Bar.new).这使测试与内部实现的联系不再那么紧密.

Incidentally, although it works I'm not a big fan of the Bar.stub!(:new) pattern; I usually prefer to pass collaborators in via optional arguments, e.g. @it.frob!(@bar). When not given an explicit argument (e.g. in the production code), the collaborator can be defaulted: def frob!(bar=Bar.new). This keeps the tests a little less bound to internal implementation.

这篇关于rspec模拟:在其中“期望"验证期望方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-22 20:29