ActionMailer::Base.deliveries.size
已经改变了1,但是被改变了2'after_create
挂钩触发verfiy_mailer.rb
# frozen_string_literal: true
class VerifyMailer < ApplicationMailer
def verification_email(user)
@user = user
mail(to: user.email, subject: 'verification code')
end
end
verify_mailer_spec.rb
# frozen_string_literal: true
require 'rails_helper'
# include ActiveJob::TestHelper
RSpec.describe VerifyMailer, type: :mailer do
let(:user) { create(:user) }
let(:mail) { VerifyMailer.verification_email(user).deliver_now }
it 'renders the receiver email' do
expect(mail.to).to eq([user.email])
end
it 'renders the subject' do
expect(mail.subject).to eq('verification code')
end
it 'renders the sender email' do
expect(mail.from).to eq(['[email protected]'])
end
end
user.rb
# frozen_string_literal: true
class User < ApplicationRecord
after_create :send_user_otp
attr_writer :login
# Include default devise modules. Others available are:
# :confirmable, :lockable, :timeoutable, :trackable and :omniauthable ,
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :validatable, authentication_keys: [:username]
has_many :payments
validates :email, :username, presence: true, uniqueness: true
validates :username, format: { with: /\A[a-zA-Z0-9_.]*\z/,
message: ' only allow letter, number, underscore and punctuation marks' }
# Loggin with user_name
def login
@login || username
end
def send_user_otp
unverify!
otp = generate_codes
update_column(:otp_code, otp)
VerifyMailer.verification_email(self).deliver_now
touch(:otp_sent_at)
end
def unverify!
update_column(:verified, false)
end
def generate_codes
loop do
code = rand(0o00000..999_999).to_s
break code unless code.length != 6
end
end
end
我添加了 config.action_mailer.delivery_method = :test 到 enviroment/test.rb
我还使用 factory_bot_rails 创建用户
FactoryBot.define do
factory :user do
sequence(:email) { |n| "person#{n}@example.com" }
sequence(:username) { |n| "user#{n}" }
password { '!Mutebi2' }
password_confirmation { '!Mutebi2' }
end
end