【发布时间】:2016-02-04 18:02:42
【问题描述】:
我正在尝试从我的模型中测试下面看到的 set_random_token 方法
class Invitation < ActiveRecord::Base
has_and_belongs_to_many :users
validates :name, presence: true, uniqueness: true
validates :number_of_uses, presence: true, numericality: true
validates :token, presence: true, uniqueness: true, format: /\A[0-9A-F]+\z/i
before_create :set_random_token
private
def set_random_token
random_hex = SecureRandom.hex(8)
self.token = random_hex
end
end
这是我的邀请规范中的部分
it 'verifies that the token is set' do
@invitation = Invitation.new
@invitation.save
expect(@invitation.token).not_to be_empty
end
这是我遇到的错误
2) Invitation verifies that the token is set
Failure/Error: expect(@invitation.token).not_to be_empty
expected to respond to `empty?`
# ./spec/models/invitation_spec.rb:37:in `block (2 levels) in <top (required)>'
我对 Rails 很陌生,所以如果答案非常明显,我深表歉意。
【问题讨论】:
-
我怀疑您在保存之前遇到了验证错误。使用
save!而不是save看看是不是这样。
标签: ruby-on-rails ruby rspec