簡體   English   中英

使用 100% 覆蓋率的 rspec 為模型編寫測試用例

[英]Write test cases for model using rspec with 100% coverage

嗨,我正在使用 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%。 請幫我修復它。 提前致謝。

通過ActionMailer使用MailJet 確保ActionMailer不在測試環境中發送電子郵件:

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

並使用enqueue_email RSpec 匹配器

另外,不要這樣做:

user = FactoryBot.create(:user)

在示例范圍之外。 請參閱此進行中的rubocop-rspec cop以獲取解釋。 如果您打算在多個示例中重用記錄,請查看test-prof let_it_be

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM