rails
(11,437 views)

Rspec example for nested resource index action

A nice clean example, posted by Martin Emde on rspec-users list
Here is the correct spec for this index action:

def index
  if params[:user_id]
    @user = User.find(params[:user_id])
    @messages = @user.messages
  end
end

Here's the spec:

describe MessagesController, " handling GET /messages for a user" do

before do
@user = mock_model(User)
@messages = mock("messages")
@user.stub!(:messages).and_return(@messages)
User.stub!(:find).and_return(@user)
end

def do_get
get :index, :user_id => 1
end

it "should render index template" do
do_get
response.should render_template('index')
end

it "should find user with params[:user_id]" do
User.should_receive(:find).with(1).and_return(@user)
do_get
end

it "should get user's messages" do
@user.should_receive(:messages).and_return(@messages)
do_get
end

it "should assign the found messages for the view" do
do_get
assigns[:messages].should be(@messages)
end
end

Comments

by Jesper Laursen on Oct 01, 2007

>>

It could be nice with some more examples. E.g. new, create, delete and edit.

by Prodis on Aug 21, 2009

Thanks

Thank you for the information.

New Comment

markdown formatting permitted