【问题标题】:How would one spec ActiveRecord::Base.find(something).method with should_receive?如何使用 should_receive 规范 ActiveRecord::Base.find(something).method?
【发布时间】:2011-03-23 11:40:33
【问题描述】:

假设我们有以下代码:

class Post < ActiveRecord::Base
  def self.fix_published_times
    where(:published => true, :published_at => nil).limit(5).each do |post
      post.fix_published_at!
    end
  end
end

我应该如何指定 Post#fix_published__at! with should_receive?

【问题讨论】:

    标签: ruby-on-rails-3 rspec arel


    【解决方案1】:

    这样的事情应该可以工作:

      mock_posts = [mock("post 1"), mock("post 2")]
      Post.should_receive(:where).with(:published => true, :published_at => nil).and_return(mock_posts)
      mock_posts.each do |mp|
        mp.should_receive(:fix_published_at!).and_return(true)
      end
      Post.fix_published_times
    

    【讨论】:

    • 对不起,我没有澄清,但我想说明的是 Post#fix_published_at! 方法
    • @vrinek 根据澄清更新了答案。
    • @Ant 谢谢。现在用find_each替换each,你认为我应该问一个新问题吗?
    • @Ant,我正在尝试做同样的事情,但使用where(&lt;args&gt;).find_each do |post| 但在. and_return(mock_posts) 之后它抱怨阵列不理解for_each。对 stub(ActiveRecord::Relation) 而不是模拟执行相同操作不会引发错误,但我不知道如何访问 find_each 块。
    • @vrinek 如果使用 find_each,则不需要 where,只需执行 find_each(此处的条件)。然后只需存根 find_each 而不是测试中的 where。
    猜你喜欢
    • 1970-01-01
    • 2020-10-19
    • 1970-01-01
    • 2011-07-14
    • 1970-01-01
    • 2012-01-10
    • 1970-01-01
    • 1970-01-01
    • 2013-08-22
    相关资源
    最近更新 更多