O módulo ActionMailer foi refeito no Rails 3 e os mailers ganharam um subdiretório próprio (dentro do app/) desde então.
Nesse post vou demonstrar como testá-los no Rails using RSpec.
Supondo que temos um mailer como esse:
ruby
classNotifier < ActionMailer::Base
default from:'[email protected]'definstructions(user)
@name = user.name
@confirmation_url = confirmation_url(user)
mail to: user.email, subject:'Instructions'endend
# spec/mailers/notifier_spec.rbRSpec.describe Notifier, type::mailerdo
describe 'instructions'do
let(:user) { mock_model User, name:'Lucas', email:'[email protected]' }
let(:mail) { described_class.instructions(user).deliver_now }
it 'renders the subject'do
expect(mail.subject).to eq('Instructions')
end
it 'renders the receiver email'do
expect(mail.to).to eq([user.email])
end
it 'renders the sender email'do
expect(mail.from).to eq(['[email protected]'])
end
it 'assigns @name'do
expect(mail.body.encoded).to match(user.name)
end
it 'assigns @confirmation_url'do
expect(mail.body.encoded)
.to match("http://aplication_url/#{user.id}/confirmation")
endendend
O Rails nos possibilita criar testes bastante compreensivos para mailers.