在Rails上更新属性

时间:2012-12-17 05:25:30

标签: ruby-on-rails

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

  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)>'

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

1 个答案:

答案 0 :(得分:4)

您的deliver方法不符合您的预期:

def deliver
  sent = true
  save
end

所有这一切都是将局部变量sent设置为true,然后调用save而不进行任何更改;没有任何更改self.sent,因此invitation.sent.should == true将失败。

您希望为sent=方法提供显式接收器,以便Ruby知道您不想分配给本地变量:

def deliver
  self.sent = true
  save
end