2010-03-28 62 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