2012-04-23 1 views
0

私は比較的新しいレールです。なぜこのrspecテストが失敗するのか分かりません。属性が設定されているかどうかをテストするのに失敗した単純なrspecモデルテスト

Modelクラス

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 ==) 

招待モデルは、トークンを持っています。何か案は?ありがとう!

答えて

3

before_createは、新しいオブジェクトのsaveより前に実行されます。すべてInvitation.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" 
+1

あなたは/招待状を作成し保存する前に、あなたはそれをスタブしましたか? – James

+0

ええ、ありがとう!それを解決! :) – Karan

関連する問題