Rspec mocks: verify expectations in it “should” methods

assertionsmockingrspec

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.

here's a small example:

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

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 ???

Best Answer

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

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.