我正在尝试测试保存模型时是否使用了特定的邮件程序类。在我的模型中,我有:
class Foo < ActiveRecord::Base
def send_email
if some_condition
FooMailer.welcome.deliver_now
else
FooBarMailer.welcome.deliver_now
end
end
def
在我对Foo课程的测试中,我有以下内容
it 'uses the foo bar mailer' do
foo_mailer = class_spy(FooMailer)
subject.send_email
# some_condition will evaluate to false here, so we'll use the FooMailer
expect(foo_mailer).to have_received :welcome
end
当我运行此测试时,它失败了:
(ClassDouble(FooMailer) (anonymous)).welcome(*(any args))
expected: 1 time with any arguments
received: 0 times with any arguments
答案 0 :(得分:3)
问题似乎是你没有用间谍换掉你邮件的当前定义,所以你的间谍没有收到任何消息。要替换它,您可以使用stub_const
方法:
it 'uses the foo bar mailer' do
foobar_mailer = class_spy(FooBarMailer)
stub_const('FooBarMailer', foobar_mailer)
subject.send_email
# some_condition will evaluate to false here, so we'll use the FooBarMailer
expect(foobar_mailer).to have_received :welcome
end