[rspec-devel] If you set an expectation on something that's already stubbed, should it return the stubbed value?

Pat Maddox pergesu at gmail.com
Sat Sep 13 13:56:37 EDT 2008

I'm pretty set on this (though I'll hold off on making changes
until I feel all opinions are given thorough discussion).  But there's
one case where it's not 100% clear to me what to do were we to make
these changes.

Here's an example I wrote in my previous email:
it "should render a 404 when the book is not found" do
  Book.should_receive(:find).with("1").and_return nil
  get :show, :id => "1"
  response.code.should == "404"

Now, I actually wouldn't write that example.  I'd write it as:
it "should render a 404 when the book is not found" do
  Book.stub!(:find).and_return nil
  get :show, :id => "1"
  response.code.should == "404"

There's no reason to set an expectation there, the best way to express
the intent of that example is to stub it and return nil, indicating
that we expect different behavior when it's nil.  Anyway, I used
should_receive in the previous email in case anyone picked up on this
and discussed that instead instead of the intent of the email.

So this begs the question, in my mind, what happens when you do:
it "should render a 404 when the book is not found" do
  get :show, :id => "1"
  response.code.should == "404"

My inclination is that it would work the same as the expectation - it
would just return the same value as was originally stubbed.  The
difference is that doing this stub would effectively be a noop.  Now I
CAN see the point that you're re-stubbing this method and it would
maybe clear out any existing stubs...but again I think it's a bad idea
to rely on the reader's knowledge that stub!, by default, returns nil.
Then again, it is a tad weird that stub! would set it up to return nil
in one context, but some different value in another context.

Over all, I think consistency with the expectation API, as well as
encouraging developers to express intent better in their examples,
wins out.


More information about the rspec-devel mailing list