【问题标题】:Stubbing ActiveRecord dynamic finders with RSpec使用 RSpec 存根 ActiveRecord 动态查找器
【发布时间】:2011-12-29 08:05:22
【问题描述】:

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

这是模型

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 做什么来帮助它通过。由于使用了动态查找器,我不确定如何正确模拟它。

【问题讨论】:

    标签: ruby-on-rails activerecord rspec rspec2


    【解决方案1】:

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

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

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

    user.stub_chain(:favorites, :find_by_place_id)
    

    【讨论】:

    • 我尝试了各种版本,并从 :favorites 存根返回 nil,但没有运气。问题不在于该方法不是预期的,而在于它需要返回 find_by_place_id 可以操作的东西,而它不能对 nil 进行操作。
    • @RyanW 对,尝试从存根的favorites 方法返回空对象。编辑了答案。
    【解决方案2】:
    favorite = double('Favorite')
    user.stub_chain(:favorites, :find_by_place_id) { favorite }
    

    【讨论】:

      猜你喜欢
      • 2015-02-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多