0

I have this simplified model:

class Contract < ActiveRecord::Base

  belongs_to :user   belongs_to :plan

  before_validation :set_default_is_voided   
  before_validation :set_default_expiration

  validates :user, presence: true
  validates :plan, presence: true
  validates :contract_date, presence: true
  validates :is_voided, presence: true
  validates :expiration, presence: true

  protected

  def set_default_is_voided
    if self.is_voided.nil?
      self.is_voided = false
      ap self.is_voided.present?
      ap self.is_voided
    end
  end

  def set_default_expiration
    if self.contract_date.present?
      self.expiration = self.contract_date+1.month
    end
  end

end

And this rspec simplified test:

context "Should create default values" do
  it "Have to create is_voided" do
    user = FactoryGirl.create(:user)
    plan = FactoryGirl.create(:planContract)
    ap "HERE"
    contractDefault = FactoryGirl.create(:contractDefault, plan: plan, user: user)
    ap contractDefault
    expect(contractDefault.is_voided).to eq(false)
  end
  it "Have to create expiration" do
    #expect(contract.expiration).should eq(Date.today()+1.month)
  end
end

FactoryGirl:

FactoryGirl.define do
  factory :contractVoid, class:Contract do
  end
  factory :contractDefault, class:Contract do
    contract_date Date.today
  end
end

This test fail with an 'is_voided can't be blank'.

And the question is: Why the method "set_default_is_voided" in before_validation don't pass the presence true validation? Moreover, the self.is_voided.present? return false, why is it happing?

Peter Alfvin
  • 28,599
  • 8
  • 68
  • 106
ppascualv
  • 1,137
  • 7
  • 21

1 Answers1

1

You answered your own question as to why set_default_is_voided doesn't pass the the presence: true validation, namely that self.is_voided.present? returns false, which is how presence: true is determined.

self.is_voided.present? returns false because false.present? == false per A concise explanation of nil v. empty v. blank in Ruby on Rails

See Rails: how do I validate that something is a boolean? for one way to validate that a boolean field is not nil.

See http://www.quora.com/Why-does-Rails-make-false-blank-true for a Q&A on the motivation behind the definition of blank?.

Community
  • 1
  • 1
Peter Alfvin
  • 28,599
  • 8
  • 68
  • 106