我试图通过 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 回调,该回调仅在事务完成后运行。
关于ruby-on-rails - Rails after_save 回调被多次调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7603448/