Reputation: 15094
I am relatively new to rails, and I am not sure why this rspec test is failing.
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. Any ideas? Thanks!
Upvotes: 0
Views: 409
Reputation: 4807
before_create
runs before save
on new objects. All Invitation.new
does is instantiate a new invitation object. You need to either save after you call new or just create the invitation object to begin with.
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"
Upvotes: 3