rspec模拟:验证它的"应该"方法的期望?

Der*_*ley 3 rspec mocking assertions

我正在尝试使用rspec的模拟设置我可以在"应该"方法中验证的期望......但我不知道如何做到这一点......当我在模拟上调用.should_receive方法时,它在before:all方法退出时立即验证预期的调用.

这是一个小例子:

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
Run Code Online (Sandbox Code Playgroud)

如何在"it"应该"'方法中验证预期的呼叫?我需要使用mocha或其他模拟框架而不是rspec吗?要么 ???

Avd*_*vdi 8

我将对此采取另一种措施,因为从最初的答案和答案中可以清楚地看出,对于你想要完成的事情存在一些困惑.如果这更接近你想要做的事,请告诉我.

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
Run Code Online (Sandbox Code Playgroud)

顺便说一下,虽然它有效但我并不是这种Bar.stub!(:new)模式的忠实粉丝; 我通常喜欢通过可选参数传递协作者,例如@it.frob!(@bar).如果没有给出明确的参数(例如在生产代码中),协作者可以默认:def frob!(bar=Bar.new).这使得测试对内部实现的限制更少.