如何测试模型中是否存在回调,特别是通过创建记录触发的回调,例如after_create
or after_commit on: :create
?
这是一个带有它调用的 (empty) 方法的示例回调。
# app/models/inbound_email.rb
class InboundEmail < ActiveRecord::Base
after_commit :notify_if_spam, on: :create
def notify_if_spam; end
end
这是使用 RSpec 3 的待定规范。
# spec/models/inbound_email_spec.rb
describe InboundEmail do
describe "#notify_if_spam" do
it "is called after new record is created"
end
end
使用消息期望来测试方法是否被调用似乎是要走的路。例如:
expect(FactoryGirl.create(:inbound_email)).to receive(:notify_if_spam)
但这不起作用。另一种方法是测试当一个记录被创建时,被调用的方法内部发生了一些事情(例如发送的电子邮件、记录的消息)。这意味着该方法确实被调用,因此存在回调。但是,我发现这是一个草率的解决方案,因为您真的在测试其他东西(例如发送的电子邮件、记录的消息),所以我不是在寻找这样的解决方案。