1

我有两个模型:

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

这是解决方案控制器:

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>    
4

2 回答 2

2

这是因为您构建解决方案,而不是创建。所以在你的数据库中没有。

制作

  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
于 2010-03-28T17:43:40.830 回答
0

我想出了我的编辑,当从参数中完成查找时,它们是字符串而不是实际的对象或整数,所以不是:

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

我需要

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

但是非常感谢你让我朝着正确的方向前进!

于 2010-03-29T00:27:33.627 回答