繁体   English   中英

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

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

我对Rails比较陌生,我不确定为什么rspec测试失败。

模型类

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

测试

  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

错误:

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

邀请模型具有token:string属性。 有任何想法吗? 谢谢!

save新对象之前, before_create运行。 Invitation.new所做的全部都是实例化一个新的邀请对象。 您需要在调用new之后保存或只创建邀请对象。

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

要么

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