用 secure_random 存根 rspec 中的随机值

stub random value in rspec with secure_random

我正在尝试为我的 gem 编写规范,它生成 otp 并将其保存在数据库中。现在我正在为它编写规范。所以基本上我有三种方法 generate_otp!regenerate_otp!verify_otp(otp)generate_otp! 的作用是调用一个方法 generate_otp,其中包含三个变量

  1. otp_code - 基本上是使用 secure_random
  2. 生成的随机值
  3. otp_verified - 一个布尔值,用于设置是否验证 otp 的状态
  4. otp_expiry_time - 设置 otp 的到期时间,可由 rails 应用程序在配置中设置。

这三个也是我的数据库的列。

现在 generate_otp 我正在调用 active_recordssave 方法将值保存到数据库。

现在为了测试,我在 :memory: 中使用并在 table 中存储值。测试后我正在删除数据库。现在我不知道如何存根随机生成的值并测试值是否分配给所有三列,即 otp_codeotp_verifiedotp_expiry_time.

这是我需要测试的方法的代码。

def generate_otp
    self.otp_verified = false
    self.otp_expiry_time = OtpGenerator::configuration.otp_expiry_time 
    self.otp_code = SecureRandom.hex(4)
  end

def generate_otp!
   generate_otp
   save
end

有什么帮助吗?我还检查了这个 question, but not much helpful. It's first time i am writing specs and really don't have that much experience with rspecs. I have also studied the official documentation 的模拟和存根,但我真的很困惑。

更新:otp_spec代码

require 'spec_helper'

describe OtpGenerator do
  
  let(:user) { build_mock_class.new() }
  before(:all) { create_table }
  after(:all) { drop_table }

  describe '#generate_otp' do
    it 'generate otp and save it' do
      user.generate_otp!
      
    end
  end

  describe '#regenerate_otp' do
    it 'regenerate otp and save it' do
      
    end
  end

  describe '#verify_otp' do
    it 'verifies otp' do
      
    end
  end

  def build_mock_class
    Class.new(ActiveRecord::Base) do
      self.table_name = 'mock_table'
      include OtpGenerator
    end
  end

  def create_table
    ActiveRecord::Base.connection.create_table :mock_table do |t|
      t.string :otp_code
      t.boolean :otp_verified
      t.datetime :otp_expiry_time
    end
  end

  def drop_table
    ActiveRecord::Base.connection.drop_table :mock_table
  end
end

rspec 中删除 SecureRandom 方法的直接方法如下:

before { allow(SecureRandom).to receive(:hex).with(4).and_return('abcd1234') }

然后您可以检查 'abcd1234' 是否存储在数据库中。为了保持测试干燥,您可能还希望将其作为变量引用,例如let(:random_value) { 'abcd1234' }.