callbacks_test.rb 2.2 KB
Newer Older
1 2 3 4 5
# encoding: utf-8
require 'cases/helper'

class Dog
  include ActiveModel::Validations
6
  include ActiveModel::Validations::Callbacks
7

8
  attr_accessor :name, :history
9

10 11
  def initialize
    @history = []
12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77
  end
end

class DogWithMethodCallbacks < Dog
  before_validation :set_before_validation_marker
  after_validation :set_after_validation_marker

  def set_before_validation_marker; self.history << 'before_validation_marker'; end
  def set_after_validation_marker;  self.history << 'after_validation_marker' ; end
end

class DogValidtorsAreProc < Dog
  before_validation { self.history << 'before_validation_marker' }
  after_validation  { self.history << 'after_validation_marker' }
end

class DogWithTwoValidators < Dog
  before_validation { self.history << 'before_validation_marker1' }
  before_validation { self.history << 'before_validation_marker2' }
end

class DogValidatorReturningFalse < Dog
  before_validation { false }
  before_validation { self.history << 'before_validation_marker2' }
end

class DogWithMissingName < Dog
  before_validation { self.history << 'before_validation_marker' }
  validates_presence_of :name
end

class CallbacksWithMethodNamesShouldBeCalled < ActiveModel::TestCase

  def test_before_validation_and_after_validation_callbacks_should_be_called
    d = DogWithMethodCallbacks.new
    d.valid?
    assert_equal ['before_validation_marker', 'after_validation_marker'], d.history
  end

  def test_before_validation_and_after_validation_callbacks_should_be_called_with_proc
    d = DogValidtorsAreProc.new
    d.valid?
    assert_equal ['before_validation_marker', 'after_validation_marker'], d.history
  end

  def test_before_validation_and_after_validation_callbacks_should_be_called_in_declared_order
    d = DogWithTwoValidators.new
    d.valid?
    assert_equal ['before_validation_marker1', 'before_validation_marker2'], d.history
  end

  def test_further_callbacks_should_not_be_called_if_before_validation_returns_false
    d = DogValidatorReturningFalse.new
    output = d.valid?
    assert_equal [], d.history
    assert_equal false, output
  end

  def test_validation_test_should_be_done
    d = DogWithMissingName.new
    output = d.valid?
    assert_equal ['before_validation_marker'], d.history
    assert_equal false, output
  end

end