0

如何测试模型中是否存在回调,特别是通过创建记录触发的回调,例如after_createor 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)

但这不起作用。另一种方法是测试当一个记录被创建时,被调用的方法内部发生了一些事情(例如发送的电子邮件、记录的消息)。这意味着该方法确实被调用,因此存在回调。但是,我发现这是一个草率的解决方案,因为您真的在测试其他东西(例如发送的电子邮件、记录的消息),所以我不是在寻找这样的解决方案。

4

1 回答 1

3

我认为 Frederick Cheung 是对的。这应该有效。您的示例的问题是在设置期望之前已经调用了回调。

describe InboundEmail do
  describe "#notify_if_spam" do
    it "is called after new record is created" do
      ie = FactoryGirl.build(:inbound_email)
      expect(ie).to receive(:notify_if_spam)
      ie.save!
    end
  end
end
于 2014-10-23T16:53:51.590 回答