Basic Sample of Action Mailer with RSpec in Rails4


This article shows how to generate action mailer class, to setup cofiguration, to test the function.


🐰 Generate Mailer Class

At first, you should create Action Mailer Class.

$ rails g mailer message hello
create app/mailers/message.rb
create app/mailers/application_mailer.rb
invoke haml
create app/views/message
create app/views/message/hello.text.haml
invoke rspec
create spec/mailers/message_spec.rb
create spec/fixtures/message/hello
create spec/mailers/previews/message_preview.rb

🍣 Mailer Code

You can customize your mail content to app/mailer/message_mailer.rb:

# app/mailer/message_mailer.rb
class MessageMailer < ActionMailer::Base
default from: 'noreply@exmpale.com'

def hello(name)
@name = name
mail to: 'send_to@example.com', subject: 'Hello'
end
end

🎂 Configuration

Following configuration is for development:

# config/environments/development.rb
AppName::Application.configure do
config.action_mailer.raise_delivery_errors = true

config.action_mailer.default_url_options = { host: "localhost", port: 3000 }
config.action_mailer.delivery_method = :smtp
config.action_mailer.smtp_settings = {
address: "SMTP MAIL SERVER",
port: 587,
domain: 'DOMAIN',
user_name: "USER NAME FOR AUTHORIZATION TO MAIL SERVER",
password: "USER PASSWORD FOR AUTHORIZATION TO MAIL SERVER"
}
end

In addition, a test configuration is as follows:

# config/environments/test.rb
AppName::Application.configure do
config.action_mailer.delivery_method = :test
end

🐡 RSpec

These specs should get you what you want.

# spec/mailers/message_mailer_spec.rb
require 'spec_helper'

describe MessageMailer do
describe 'hello' do
let(:name) { 'John' }
let(:mail) { described_class.hello(name).deliver_now }

it 'renders the subject' do
expect(mail.subject).to eql('Hello')
end

it 'renders the receiver email' do
expect(mail.to).to eql(['send_to@example.com'])
end

it 'renders the sender email' do
expect(mail.from).to eql(['noreply@exmpale.com'])
end

it 'assigns @name' do
expect(mail.body.encoded).to match(name)
end
end
end

😼 Special Thanks

🖥 Recommended VPS Service

VULTR provides high performance cloud compute environment for you. Vultr has 15 data-centers strategically placed around the globe, you can use a VPS with 512 MB memory for just $ 2.5 / month ($ 0.004 / hour). In addition, Vultr is up to 4 times faster than the competition, so please check it => Check Benchmark Results!!