我正在尝试为我的 gem 编写规范,它生成 otp 并将其保存在数据库中。现在我正在为它编写规范。所以基本上我有三种方法 generate_otp!
、regenerate_otp!
、verify_otp(otp)
。 generate_otp!
的作用是调用包含三个变量的方法 generate_otp
otp_code
- 基本上是使用 secure_random 生成的随机值otp_verified
- 一个 bool 值,用于设置 otp 是否已验证的状态otp_expiry_time
- 设置 otp 的到期时间,可以由 Rails 应用在配置中设置。
这三个也是我的数据库的列。
在 generate_otp
之后,我正在调用 active_records
的 save
方法将值保存到 db。
现在为了测试,我在 :memory:
中使用并将值存储在表中。测试后我正在删除数据库。现在我不知道如何 stub 随机生成的值并测试是否将值分配给所有三列,即 otp_code
、otp_verified
、otp_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 ,但帮助不大。这是我第一次编写规范,并且对 rspecs 真的没有那么多经验。我也研究过官方documentation对于模拟和 stub ,但我真的很困惑。
更新: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' }
。
关于ruby-on-rails - 使用 secure_random stub rspec 中的随机值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38370512/