2010-03-08 105 views
0

我有一個名爲SolutionsController的控制器,其索引操作根據params[:user_id]的值而不同。如果它爲零,那麼它只是顯示我網站上的所有解決方案,但如果它不是零,那麼它會顯示給定用戶標識的所有解決方案。使用RSpec在Rails控制器中測試範圍查找

這就是:

def index 
    if(params[:user_id]) 
     @solutions = @user.solutions.find(:all) 
    else 
     @solutions = Solution.find(:all) 
    end 
    end 

@user確定這樣的:

private 

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

我有一個RSpec測試,測試指標作用,如果用戶是零:

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 

然而,有人能告訴我如何爲我的控制器的另一半寫一個類似的測試,當t他的用戶名不是零?

喜歡的東西:

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 

但是,這並不工作。有人可以幫我嗎?

回答

0

嘗試和存根出找到用戶的時候user_id是不是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