嵌套资源测试RSpec

时间:2010-03-28 17:14:14

标签: ruby-on-rails unit-testing rspec nested-resources

我有两种模式:

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 个答案:

答案 0 :(得分: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

答案 1 :(得分:0)

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

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

我需要

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

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