Testing a scoped find in a Rails controller with RSpec
I've got a controller called SolutionsController whose index action is different depending on the value of params[:user_id]
. If its nil, then it simply displays all of the solutions on my site, but if its not nil, then it displays all of the solutions for the given user id.
Here it is:
def index
if(params[:user_id])
@solutions = @user.solutions.find(:all)
else
@solutions = Solution.find(:all)
end
end
and @user
is determine开发者_开发技巧d like this:
private
def load_user
if(params[:user_id ])
@user = User.find(params[:user_id])
end
end
I've got an Rspec test to test the index action if the user is nil:
describe "GET index" do
context "when user_id is nil" do
it "should find all of the solutions" do
Solution.should_receive(:find).with(:all).and_return(@solutions)
get :index
end
end
end
however, can someone tell me how I write a similar test for the other half of my controller, when the user id isn't nil?
Something like:
describe "GET index" do
context "when user_id isn't nil" do
before(:each) do
@user = Factory.create(:user)
@solutions = 7.times{Factory.build(:solution, :user => @user)}
@user.stub!(:solutions).and_return(@solutions)
end
it "should find all of the solutions owned by a user" do
@user.should_receive(:solutions).and_return(@solutions)
get :index, :user_id => @user.id
end
end
end
But that doesn't work. Can someone help me out?
try and stub out the find on the User for when the user_id is not nil
describe "GET index" do
context "when user_id isn't nil" do
before(:each) do
@user = Factory.create(:user)
@solutions = 7.times{Factory.build(:solution, :user => @user)}
@user.stub!(:solutions).and_return(@solutions)
User.stub(:find).and_return(@user)
end
it "should find all of the solutions owned by a user" do
@user.should_receive(:solutions).and_return(@solutions)
get :index, :user_id => @user.id
end
end
end
精彩评论