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

时间:2012-04-23 20:42:03

标签: ruby-on-rails rspec

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

邀请模型有一个令牌:字符串属性。有任何想法吗?谢谢!

1 个答案:

答案 0 :(得分:3)

before_createsave之前在新对象上运行。所有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"