【发布时间】:2018-03-28 15:50:00
【问题描述】:
您好,我正在使用 ruby-2.5.0 和 rails 5.0 开发 RoR 项目。我有一个模型 forgot_password ,其中定义了一个类方法来创建记录,如下所示:-
forgot_password.rb
# frozen_string_literal: true
class ForgotPassword < ApplicationRecord
before_create :create_token
def self.create_record
self.create!(expiry: Time.zone.now +
ENV['VALIDITY_PERIOD'].to_i.hours)
end
private
def create_token
self.token = SecureRandom.urlsafe_base64(nil, false)
end
end
我想使用 stub 或 factory_girl gem 为其编写单元测试。
spec/models/forgot_password_spec.rb
# frozen_string_literal: true
require 'rails_helper'
describe ForgotPassword do
let(:forgot_password) do
described_class.new()
end
describe 'create_record' do
context 'with forgot_password class' do
subject { forgot_password.create_record.class }
it { is_expected.to eq ForgotPassword }
end
end
end
但它的抛出错误undefined method create_record for #<ForgotPassword:0x000000000622bc98> 请帮助我如何测试我的模型。提前致谢。
【问题讨论】:
-
停止实例化所描述类的实例?
-
对不起,我没有明白你的意思
-
如何在有类方法和 before_create 回调的地方测试我的模型?
标签: ruby-on-rails unit-testing rspec