我正在尝试通过mixin注入(inject)after_save回调,但是我的rspec测试告诉我,当调用create方法时,该回调被调用了两次。为什么该方法被调用两次?

以下rspec测试失败

it 'should call callback' do
  Product.any_instance.should_receive(:update_linkable_attachments).once
  Product.create(:name=>'abc')
end

失败消息是:
Failure/Error: Unable to find matching line from backtrace
   (#<Product:0xb7db738>).update_linkable_attachments(any args)
       expected: 1 time
       received: 2 times

这是代码
module MainModuleSupport
  def self.included(base)
    base.instance_eval("after_save :update_linkable_attachments")
  end

  def update_linkable_attachments
    LinkedAttachment.delay.create_from_attachment self
  end
end

class Product < ActiveRecord::Base
  include MainModuleSupport
  ...

end

Product类具有其他代码,但没有任何其他回调。

最佳答案

after_save是事务的一部分,因此,如果您还需要保存其他关联的对象,则可以多次调用它。在这种情况下,我通常会从after_save回调转移到after_commit回调,该回调仅在事务完成后才运行。

10-07 19:07
查看更多