rspec 当调用父方法时期望子方法接收方法

rspec expect child to receive method when parent method is called

class Post
  has_many :comments

  after_update :update_comments

  def update_comments(user)
    comments.where(user: user).each do |comment|
      # binding.pry
      comment.do_something
    end
  end
end

class Comment
  belongs_to :post

  def do_something
    'Ok, I will'
    # binding.pry
  end
end

这是我的问题:

RSpec.describe Post do
  describe '#update_comments' do
    let(:post) { create :post }
    let(:comment) { create :comment, post: post }

    it 'triggers comment.do_something'
      comment = post.comments.first
      expect(comment).to receive(:do_something)
      post.update(title: 'new title')
    end
  end
end

我收到这个错误:

(#<Comment id: 1, ..., created_at: "2018-06-15 01:31:33", updated_at: "2018-05-16 02:51:39">).api_update(*(any args))
       expected: 1 time with any arguments
       received: 0 times with any arguments

但是如果我在其中一个(或两个)def(s) 中使用 binding.pry,我会得到控制台,所以我知道它实际上被调用了。

我将 RSpec 中的 comment 变量与 Comment class 中的 self 进行了比较,它们匹配。我尝试在 RSpec 中使用 post.reloadcomment.reload 来确保关联牢固。不知道我还能做什么。

它在我所说的应该接收的方法中触发 pry 的事实让我很困惑。

我错过了什么?

经过更多的挖掘,问题是我的 comment 变量实际上与 RSpec 在循环中看到的变量并不完全相同。它们的区别在于动态分配的 Rails 对象 ID。

我需要使用间谍或存根方法来避免这个问题。