[rspec-users] Rspec Nested Resources: Can someone offer an 'update' example?

Mike Mazur mmazur at gmail.com
Mon Jan 17 18:54:09 EST 2011


Hi,

On Fri, Jan 14, 2011 at 05:53, SpringChicken
<anonymousleggingsgenie at gmail.com> wrote:
> I've just spent a day trying to write up a basic update spec for a
> nested resource - all without avail. I'm quite new to RSpec & not sure
> what I'm doing wrong. I can't seem to get a stub that recognises the
> required association to the parent object. I've tried factories and
> outright database calls, none of which seem to catch the
> should_receive. If anyone could offer a basic example of the nested
> equivalent of something like the following, I'd be very appreciative.
>
>        it "updates the requested post" do
>          Post.stub(:find).with("14") { mock_post }
>          mock_post.should_receive(:update_attributes).with({'these'
> => 'params'})
>          put :update, :id => "14", :post => {'these' => 'params'}
>        end
>
> Controller action here:
>
>  def update
>    @comment = Comment.find(params[:id])
>    respond_to do |format|
>      if @comment.update_attributes(params[:comment])
>        flash[:notice] = 'Post successfully updated'
>        format.html { redirect_to(@comment.post) }
>        format.xml  { head :ok }
>      else
>        format.html { render :action => "edit" }
>        format.xml  { render :xml => @comment.errors, :status
> => :unprocessable_entity }
>      end
>    end
>
>  end

In your spec you are stubbing Post so that Post.find(14) returns
mock_post. Then you pass 14 as the :id parameter to the update action.

In the update action, you use the :id parameter to find a *Comment*
not a Post. So, mock_post is never actually used and the
should_receive is thus never triggered.

Mike


More information about the rspec-users mailing list