methodofaction
methodofaction

Reputation: 72395

Updating an attribute on Rails

I know this is a very simple question, but I can't seem to be able to fix this despite many variations:

  it "will send an email" do
    invitation = Invitation.new
    invitation.email = "[email protected]"
    invitation.deliver 
    invitation.sent.should == true
  end  

My model:

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

This outputs:

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

How do I set the value and then save it within the model itself?

Upvotes: 1

Views: 69

Answers (1)

mu is too short
mu is too short

Reputation: 434665

Your deliver method doesn't do what you think it does:

def deliver
  sent = true
  save
end

All that does is set the local variable sent to true and then it calls save without anything being changed; nothing changes self.sent so invitation.sent.should == true will fail.

You want to supply an explicit receiver for the sent= method so that Ruby knows you don't want to assign to a local variable:

def deliver
  self.sent = true
  save
end

Upvotes: 4

Related Questions