简体   繁体   中英

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.

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!

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"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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