2010-03-28 88 views
1

我有兩個型號:嵌套資源測試RSpec的

class Solution < ActiveRecord::Base 
    belongs_to :owner, :class_name => "User", :foreign_key => :user_id 
end     

class User < ActiveRecord::Base 
    has_many :solutions 
end 

與以下路由:

map.resources :users, :has_many => :solutions 

這裏是SolutionsController:

class SolutionsController < ApplicationController 
    before_filter :load_user 

    def index 
    @solutions = @user.solutions 
    end 

    private 
    def load_user 
     @user = User.find(params[:user_id]) unless params[:user_id].nil? 
    end 
end 

任何人可以幫助我寫作索引行動的測試?到目前爲止,我曾嘗試以下,但它不工作:

describe SolutionsController do 
    before(:each) do 
    @user = Factory.create(:user) 
    @solutions = 7.times{Factory.build(:solution, :owner => @user)} 
    @user.stub!(:solutions).and_return(@solutions) 
    end 

    it "should find all of the solutions owned by a user" do 
    @user.should_receive(:solutions) 
    get :index, :user_id => @user.id 
    end 
end 

而且我得到以下錯誤:

Spec::Mocks::MockExpectationError in 'SolutionsController GET index, when the user owns the software he is viewing should find all of the solutions owned by a user' 
#<User:0x000000041c53e0> expected :solutions with (any args) once, but received it 0 times 

預先感謝所有幫助。

編輯:

感謝您的回答,我接受它,因爲它得到了我這麼多的更遠,除了我得到另一個錯誤,而我不能完全弄清楚它的努力告訴我:

一旦我創建瞭解決方案,而不是建立他們,我添加了User.find的存根,我看到以下錯誤:

NoMethodError in 'SolutionsController GET index, when the user owns the software he is viewing should find all of the solutions owned by a user' 
undefined method `find' for #<Class:0x000000027e3668>  

回答

2

這是因爲... e您構建解決方案,而不是創建。所以沒有在你的數據庫中。

製造

before(:each) do 
    @user = Factory.create(:user) 
    @solutions = 7.times{Factory.create(:solution, :owner => @user)} 
    @user.stub!(:solutions).and_return(@solutions) 
    end 

你嘲笑的用戶實例,但也有用戶的另一個實例可以實例化。您需要添加模擬User.find太

before(:each) do 
    @user = Factory.create(:user) 
    @solutions = 7.times{Factory.create(:solution, :owner => @user)} 
    User.stub!(:find).with(@user.id).and_return(@user) 
    @user.stub!(:solutions).and_return(@solutions) 
    end 
0

我想通了,我的編輯,當發現從PARAMS做,他們,而不是實際的對象或整數串,所以不是:

User.stub!(:find).with(@user.id).and_return(@user) 

我需要

User.stub!(:find).with(@user.id.to_s).and_return(@user) 

但謝謝你,你讓我在正確的方向這麼多shingara!

Joe