RSpec:测试邮件程序只调用一次

时间:2014-09-18 21:06:21

标签: ruby-on-rails rspec stub

我有Mailer看起来像这样:

class EventMailer < BaseMailer
  def event_added(user_id, event_id)
    # do stuff and email user about the event
  end
end

我在EventMailer类中调用此Event

class Event < Task
  def notify_by_email(user)
    EmailLog.send_once(user.id, id) do
      EventMailer.delay(queue: 'mailer').event_added(user.id, id)
    end
  end
end

其中EmailLog是记录已发送电子邮件的类。 Sidekiq添加了.delay

但是当我尝试测试每个事件和用户只调用一次#notify_by_email时,我的规范就失败了:

1) Event#notify_by_email only sends once per user
     Failure/Error: expect(EventMailer).to receive(:event_added).once
       (<EventMailer (class)>).event_added(any args)
           expected: 1 time with any arguments
           received: 0 times with any arguments

规范如下:

let(:owner) { User.make! }
let(:product) { Product.make! }
let(:event) { Task.make!(user: owner, product: product) }

describe '#notify_by_email' do
  before do
    EventMailer.stub(:delay).and_return(EventMailer)
  end

  it 'only sends once per user' do
    event.notify_by_email(owner)
    event.notify_by_email(owner)

    expect(EventMailer).to receive(:event_added).once
  end
end

有关此规范失败原因以及如何解决此问题的任何见解?奇怪的是,如果我在传递给puts的块中放置EmailLog.send_once语句,它只打印一次,规范仍会报告未调用EventMailer.event_added

1 个答案:

答案 0 :(得分:11)

您的期望应在之前宣布您正在测试的代码。使用expect(...).to receive(...)基本上意味着&#34;此消息应在现在和本规范结束之间收到&#34;。因为期望是规范的最后一行,所以它失败了。

尝试之前移动它,你应该好好去:

it 'only sends once per user' do
  expect(EventMailer).to receive(:event_added).once

  event.notify_by_email(owner)
  event.notify_by_email(owner)
end