我有一个看起来像这样的邮件: class EventMailer BaseMailer def event_added(user_id, event_id) # do stuff and email user about the event endend 我在Event类中调用了这个EventMailer: class Event Task def notify_by_email(
class EventMailer < BaseMailer def event_added(user_id, event_id) # do stuff and email user about the event end end
我在Event类中调用了这个EventMailer:
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是一个记录已发送电子邮件的类. .delay由Sidekiq添加.
但是当我尝试测试每个事件和用户只调用一次#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.
您的期望应在您正在测试的代码之前声明.使用expect(…).接收(…)基本上意味着“应该在此规范的现在和结束之间接收此消息”.因为期望是您的规范的最后一行,它失败了.尝试之前移动它,你应该好好去:
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