使用具有100%覆盖率的rspec编写模型的测试用例

时间:2018-04-13 17:50:55

标签: ruby-on-rails rspec-rails rubocop-rspec

您好我正在使用ruby-2.5.0和Rails 5处理RoR项目。我有一个forgot_password模型,我正在使用rspec为它编写测试用例。 我在模型中有两种方法如下: -

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

第一种方法创建forgot_password记录,另一种方法使用mailjet发送电子邮件。 我的规格如下: -

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

当我运行RAILS_ENV=test bundle exec rake时我得到Coverage (99.58%) is below the expected minimum coverage (100.00%)请帮我写下遗失的案例。当我从send_forgot_password_email方法中删除return if Rails.env == 'test'这一行时,它涵盖了100%。请帮我修理一下。提前谢谢。

1 个答案:

答案 0 :(得分:0)

使用MailJet through ActionMailer。确保 ActionMailer 不在测试环境中发送电子邮件:

# config/environments/test.rb
config.action_mailer.delivery_method = :test

并使用 enqueue_email RSpec matcher

另外,不要这样做:

user = FactoryBot.create(:user)

在示例范围之外。请参阅 this work-in-progress rubocop-rspec cop 了解说明。 如果您打算在多个示例中重复使用该记录,请查看 let_it_be from test-prof