使用RSpec对ActiveRecord动态查找器进行存根

时间:2011-12-29 08:05:22

标签: ruby-on-rails activerecord rspec rspec2

如何在我的控制器规格中设置以下模型/规格进行模拟。

以下是模型

class User < ActiveRecord::Base
  has_many :favorites
end

class Favorite < ActiveRecord::Base
  belongs_to :user
  belongs_to :place
end

class Place < ActiveRecord::Base
  has_many :favorites, :as => :favorable
end

然后在某个时刻会检查一个地方,看看它目前是否是最喜欢的

@favorite = @current_user.favorites.find_by_place_id(@place.id)

现在,我想模仿用户的一些例子

it "should be success" do
  user = double("User")
  user.stub(:favorites)
  get :show, :id => "1081651"
  response.should be_success
end

但是,我最终得到了

undefined method `find_by_place_id' for nil:NilClass

我能做些什么:帮助它通过的最爱。由于使用了动态查找器,我不确定如何正确地模拟它。

2 个答案:

答案 0 :(得分:2)

使用null对象存根,它将忽略所有意外消息:

user.stub(:favorites).and_return(double.as_null_object)

另一种方法是使用stub_chain方法:

user.stub_chain(:favorites, :find_by_place_id)

答案 1 :(得分:1)

favorite = double('Favorite')
user.stub_chain(:favorites, :find_by_place_id) { favorite }