Rails after_save回调被多次调用

我试图通过mixin注入一个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 (#).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回调,后者仅在事务完成后运行。