I am trying to test that a specific mailer class is used when a model is saved. In my model I have:
class Foo < ActiveRecord::Base
def send_email
if some_condition
FooMailer.welcome.deliver_now
else
FooBarMailer.welcome.deliver_now
end
end
def
In my tests for Foo class I have the following
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
When I run this test it fails with:
(ClassDouble(FooMailer) (anonymous)).welcome(*(any args))
expected: 1 time with any arguments
received: 0 times with any arguments
The issue would seem to be that you haven't swapped out the current definition of your mailer class with the spy, so your spy isn't receiving any messages. To replace it, you would use the stub_const
method:
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
foo_mailer = class_spy(FooMailer).as_stubbed_const
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.