1

我知道这是一个非常简单的问题,但尽管有很多变化,我似乎无法解决这个问题:

  it "will send an email" do
    invitation = Invitation.new
    invitation.email = "host@localhost.com"
    invitation.deliver 
    invitation.sent.should == true
  end  

我的模型:

class Invitation
  include Mongoid::Document
  include Mongoid::Timestamps
  field :email, :type => String, :presence => true, :email => true
  field :sent, :type => Boolean, :default => false
  field :used, :type => Boolean, :default => false
  validates :email, :uniqueness => true, :email => true

  def is_registered?
    User.where(:email => email).count > 0
  end

  def deliver
    sent = true
    save
  end

end

这输出:

  1) Invitation will send an email
     Failure/Error: invitation.sent.should == true
       expected: true
            got: false (using ==)
     # ./spec/models/invitation_spec.rb:26:in `block (2 levels) in <top (required)>'

如何设置值,然后将其保存在模型本身中?

4

1 回答 1

4

你的deliver方法没有做你认为它做的事情:

def deliver
  sent = true
  save
end

所做的只是将局部变量设置senttrue,然后在save没有任何更改的情况下调用;没有任何改变self.sent,所以invitation.sent.should == true会失败。

您想为该sent=方法提供一个显式接收器,以便 Ruby 知道您不想分配给局部变量:

def deliver
  self.sent = true
  save
end
于 2012-12-17T05:39:43.710 回答