You can generate mailers with rails generate
(Password_reset
will be used later)
$ rails generate mailer UserMailer account_activation password_reset
The product is below
create app/mailers/user_mailer.rb #Define something like an action here
invoke erb
create app/views/user_mailer
create app/views/user_mailer/account_activation.text.erb #Email layout (text)
create app/views/user_mailer/account_activation.html.erb #Email layout (html)
ERB can be used for layout
edit_account_activation_url(@user.activation_token, email: @user.email)
And take two arguments Returns a path like the following
/account_activations/(1st argument)/edit?(2nd argument)
The following are called ** query parameters **
Written as a key / value pair with ? Email = ...
Make the view file embed the above url helper
** Instance variables **, ** Destination **, ** Title ** used in view files Define in app / mailers / user_mailer.rb`
def account_activation(user)
@user = user
mail to: user.email, subject: "Account activation"
end
If you follow the procedure You will be able to preview in your browser
The test is already described below
Cause of $ rails test
> (RED)
test/mailers/user_mailer_test.rb
require 'test_helper'
class UserMailerTest < ActionMailer::TestCase
test "account_activation" do
mail = UserMailer.account_activation
assert_equal "Account activation", mail.subject
assert_equal ["[email protected]"], mail.to
assert_equal ["[email protected]"], mail.from
assert_match "Hi", mail.body.encoded
end
.
.
.
end
config/environments/test.rb
Rails.application.configure do
.
.
.
config.action_mailer.delivery_method = :test
config.action_mailer.default_url_options = { host: 'example.com' } #Set up a test environment host
.
.
.
end
It should be $ rails test
> (GREEN)
password_reset
remains failure * assert_equal ["[email protected]"], mail.from
After fixing
It became $ rails test
> (GREEN)
Change create
action
--Send mail with ʻUserMailer.account_activation (@user)` --Change flash message --Do not log in at this point --Change redirect destination
def create
@user = User.new(user_params)
if @user.save
UserMailer.account_activation(@user).deliver_now
flash[:info] = "Please check your email to activate your account."
redirect_to root_url
else
render 'new'
end
end
Since the behavior changes, it becomes $ rails test
> (RED)
Recommended Posts