简体   繁体   English

简单的rspec模型测试无法测试是否设置了属性

[英]Simple rspec model test failing to test if attribute is set

I am relatively new to rails, and I am not sure why this rspec test is failing. 我对Rails比较陌生,我不确定为什么rspec测试失败。

Model class 模型类

class Invitation < ActiveRecord::Base
  belongs_to :sender, :class_name => "User"

  before_create :generate_token

  private 
  def generate_token
    self.token = Digest::SHA1.hexdigest([Time.now, rand].join)
  end
end

Test 测试

  it "should create a hash for the token" do
    invitation = Invitation.new
    Digest::SHA1.stub(:hexdigest).and_return("some random hash")
    invitation.token.should == "some random hash"
  end

Error: 错误:

Failure/Error: invitation.token.should == "some random hash"
       expected: "some random hash"
            got: nil (using ==)

The invitation model has a token:string attribute. 邀请模型具有token:string属性。 Any ideas? 有任何想法吗? Thanks! 谢谢!

before_create runs before save on new objects. save新对象之前, before_create运行。 All Invitation.new does is instantiate a new invitation object. Invitation.new所做的全部都是实例化一个新的邀请对象。 You need to either save after you call new or just create the invitation object to begin with. 您需要在调用new之后保存或只创建邀请对象。

Digest::SHA1.stub(:hexdigest).and_return("some random hash")
invitation = Invitation.new
invitation.save
invitation.token.should == "some random hash"

or 要么

Digest::SHA1.stub(:hexdigest).and_return("some random hash")
invitation = Invitation.create
invitation.token.should == "some random hash"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM