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

Zach Dennis zach.dennis at gmail.com
Sun Sep 14 22:34:54 EDT 2008

On Sat, Sep 13, 2008 at 1:56 PM, Pat Maddox <pergesu at gmail.com> wrote:
> 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"
> end
> 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"
> end
> 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
>  Book.stub!(:find)
>  get :show, :id => "1"
>  response.code.should == "404"
> end
> 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.

I'm pretty sure I misread your first email thinking that you wanted to
replace the usage of and_return with reliance on the stubbed out
values from the befores, which I gave a -1 to since I felt that would
provide confusion and lack of clarity. But I don't think that is at
all what you were suggesting.

To communicate back to you what I think you're suggesting... you'd
like to remove unnecessary usages of and_return when it isn't used to
exemplify the intent of an example. And your argument for principle of
least surprise I do agree with. Not that it matters, but +1.

Thanks for taking the time to share what you're thinking more than once. ;)

Zach Dennis

More information about the rspec-devel mailing list