Wednesday, August 21, 2013

ActionMailer::Base.deliveries always empty in RSpec model test in Rails 4

ActionMailer::Base.deliveries always empty in RSpec model test in Rails 4

I have the following failing test:
describe Image do
describe 'a_method' do
it 'sends email' do
Image.count.should == 1
expect do
ImageMailer.deleted_image(Image.last.id).deliver
end.to change(ActionMailer::Base.deliveries, :length)
end
end
end
And here's my mailer:
class ImageMailer < ActionMailer::Base
layout 'email'
default from: 'whee@example.com'
def deleted_image image_id, recipient='whee@example.com'
@image = Image.find(image_id)
subject = "Image email"
mail(to: recipient, subject: subject) do |format|
format.text
format.html { render layout: 'email' }
end
end
end
My test fails with Failure/Error: expect do length should have changed,
but is still 0. I have another test for my mailer itself and it passes:
describe ImageMailer do
it 'should deliver the mail' do
expect do
subject.deliver
end.to change { ActionMailer::Base.deliveries.length }.by(1)
end
end
I don't know why ActionMailer::Base.deliveries is always empty in my model
spec but not in my mailer spec. The mail obviously works. My model test
was originally different, testing whether a method on my model caused an
email to be sent, but when that failed to generate a mail delivery, I
explicitly tried the ImageMailer.deleted_image(Image.last.id).deliver line
and it didn't work. Is there something special about RSpec tests where the
object being described is a mailer class?
Here are some relevant lines from my config/environments/test.rb file:
config.action_mailer.delivery_method = :test
config.action_mailer.default_url_options = {host: 'localhost:3000'}
config.action_mailer.perform_deliveries = true

No comments:

Post a Comment