如何在我的 Controller 规范中设置以下模型/规范以进行模拟。
这是模型
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
我可以用 :favorites 做什么来帮助它通过。由于使用了动态查找器,我不确定如何正确模拟它。
最佳答案
使用空对象 stub ,它将忽略所有意外消息:
user.stub(:favorites).and_return(double.as_null_object)
另一种方法是使用stub_chain
方法:
user.stub_chain(:favorites, :find_by_place_id)
关于ruby-on-rails - 使用 RSpec stub ActiveRecord 动态查找器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8665336/