[rspec-users] basic noob question

Rick DeNatale rick.denatale at gmail.com
Sat Jul 25 11:07:54 EDT 2009

On Fri, Jul 24, 2009 at 9:40 PM, norm<codehacker at comcast.net> wrote:
> I'm struggling mightily!
> I have a controller called Govtpositions, and I'm just trying to test
> the standard Rails 'create' method. So it seems as if three examples
> would be appropriate... one to test the instantiation of the new model
> from the params hash, another to test that it was saved, and then the
> final redirection.
> So just to test the model instantiation, I have:
> describe GovtpositionsController, "POST govtpositions to create govt
> new government position" do
>  before do
>    Govtposition.stub!(:new).and_return(@govtposition)
>  end
>  it "should create a new govt position model" do
>    @govtposition = mock_model(Govtposition)
>    @params = {"name"=>"chief"}
>    Govtposition.should_receive(:new).with(@params).and_return
> (@govtposition)
>  end
> end
> But this example fails due to "Mock 'Govtposition_1001' received
> unexpected message :save with (no args)"
> Surely I should be able to test the save in a separate example, no? I
> was expecting to declare just one expectation per example, with a
> total of three for the create method. But the test failure seems to
> suggest otherwise.
> Any clarification you can offer would be much appreciated.

Well the controller code doesn't know it's under test so it will call save.

You need to stub out save, probably in the before block, to return true.

Then in the example which expects the save, set a message expectation.

I'm also not sure how your current code is actually working, since,
unless I'm mistaken, the before block runs before the example, and
therefore before you assign a (new?) value to @govtposition, so in the
before block you are stubbing whatever @govtposition refers to at that
point, probably nil.

But I also notice that you are never actually calling anything after
the message expectation, so I suspect that this is a poorly abstracted
version of your actual code.

Rick DeNatale

Blog: http://talklikeaduck.denhaven2.com/
Twitter: http://twitter.com/RickDeNatale
WWR: http://www.workingwithrails.com/person/9021-rick-denatale
LinkedIn: http://www.linkedin.com/in/rickdenatale

More information about the rspec-users mailing list