簡體   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