假设有这样的电子邮件:
class UserMailer < ApplicationMailer
def welcome_email(user)
@user = user
mail(to: @user.email, subject: 'Welcome')
end
end
然后这样发邮件:
class User < ApplicationRecord
def self.register(email, password)
user = create(email: email, password: password)
UserMailer.welcome_email(user).deliver_later
end
end
使用 deliver_later 方法需要在 application.rb 里加上:
config.active_job.queue_adapter = :sidekiq # 可以换成其它的 adapter
如果邮件模板中有外链,还需要在 environments/test.rb 里加上:
config.action_mailer.default_url_options = { host: 'test.mysite.com' }
在 user_spec.rb 里:
require 'rails_helper'
RSpec.describe User, type: :model do
describe '.register' do
include ActiveJob::TestHelper
it 'should be created mail job' do
ActiveJob::Base.queue_adapter = :test
expect {
User.register('[email protected]', '123123')
}.to have_enqueued_job.on_queue('mailers')
end
it 'should be sent welcome mail' do
expect {
perform_enqueued_jobs do
User.register('[email protected]', '123123')
end
}.to change { ActionMailer::Base.deliveries.size }.by(1)
end
it 'should be sent to the right user' do
perform_enqueued_jobs do
User.register('[email protected]', '123123')
end
mail = ActionMailer::Base.deliveries.last
expect(mail.to[0]).to eq "[email protected]"
end
end
end