0

我对 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 属性。有任何想法吗?谢谢!

4

1 回答 1

3

before_create之前save在新对象上运行。所做的只是实例化一个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"
于 2012-04-23T20:48:34.120 回答