Hi I am working on RoR project with ruby-2.5.0 and Rails 5. I have a forgot_password model and i am writting test cases for it using rspec. I have two methods in model as follows:-
class ForgotPassword < ApplicationRecord
before_create :create_token
def self.create_record(user)
forgot_password = create!(expiry: Time.zone.now + ENV['VALIDITY_PERIOD'].to_i.hours)
send_forgot_password_email user, forgot_password
forgot_password
end
def self.send_forgot_password_email(user, forgot_password)
return if Rails.env == 'test'
Mailjet::Send.create(from_email: ENV['MIALJET_DEFAULT_FROM'],
from_name: ENV['MIALJET_FROM_NAME'],
to: user.email,
subject: 'Forgot Password',
text_part: forgot_password.token)
end
private
def create_token
self.token = SecureRandom.urlsafe_base64(nil, false)
end
end
First method creates a record of forgot_password and another method send an email using mailjet. My spec is as follows:-
spec/models/forgot_password_spec.rb
require 'rails_helper'
RSpec.describe ForgotPassword, type: :model do
user = FactoryBot.create(:user)
describe '#create_record' do
it 'do not raise_error' do
expect { ForgotPassword.create_record(user) }.not_to raise_error
end
it 'increment the count of ForgotPassword' do
expect { ForgotPassword.create_record(user) }.to change(ForgotPassword, :count)
.from(0).to(1)
end
it 'return instance of ForgotPassword' do
expect(ForgotPassword.create_record(user)).to be_instance_of(ForgotPassword)
end
it 'return nil when env is test' do
expect(ForgotPassword.send_forgot_password_email(user,ForgotPassword.last)).to eq(nil)
end
end
end
When i run RAILS_ENV=test bundle exec rake
i got Coverage (99.58%) is below the expected minimum coverage (100.00%)
Please help me to write the missing case. when i remove return if Rails.env == 'test'
this line from send_forgot_password_email method it covers 100%. Please help me to fix it. Thanks in advance.
Use MailJet through ActionMailer
. Make sure ActionMailer
doesn't send out emails in the test env:
# config/environments/test.rb
config.action_mailer.delivery_method = :test
and use enqueue_email
RSpec matcher .
Also, don't do this:
user = FactoryBot.create(:user)
outside of the example scope. See this work-in-progress rubocop-rspec
cop for explanation. If your intent is to reuse the record in several examples, take a look at let_it_be
from test-prof
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.