aboutsummaryrefslogtreecommitdiffstats
path: root/activemodel/test/cases/validations/absence_validation_test.rb
blob: c05d71de5a318aeda41a61ef60b1403882e85b09 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
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
# encoding: utf-8
require 'cases/helper'
require 'models/topic'
require 'models/person'
require 'models/custom_reader'

class AbsenceValidationTest < ActiveModel::TestCase
  teardown do
    Topic.reset_callbacks(:validate)
    Person.reset_callbacks(:validate)
    CustomReader.reset_callbacks(:validate)
  end

  def test_validate_absences
    Topic.validates_absence_of(:title, :content)
    t = Topic.new
    t.title = "foo"
    t.content = "bar"
    assert t.invalid?
    assert_equal ["must be blank"], t.errors[:title]
    assert_equal ["must be blank"], t.errors[:content]
    t.title = ""
    t.content  = "something"
    assert t.invalid?
    assert_equal ["must be blank"], t.errors[:content]
    t.content = ""
    assert t.valid?
  end

  def test_accepts_array_arguments
    Topic.validates_absence_of %w(title content)
    t = Topic.new
    t.title = "foo"
    t.content = "bar"
    assert t.invalid?
    assert_equal ["must be blank"], t.errors[:title]
    assert_equal ["must be blank"], t.errors[:content]
  end

  def test_validates_acceptance_of_with_custom_error_using_quotes
    Person.validates_absence_of :karma, message: "This string contains 'single' and \"double\" quotes"
    p = Person.new
    p.karma = "good"
    assert p.invalid?
    assert_equal "This string contains 'single' and \"double\" quotes", p.errors[:karma].last
  end

  def test_validates_absence_of_for_ruby_class
    Person.validates_absence_of :karma
    p = Person.new
    p.karma = "good"
    assert p.invalid?
    assert_equal ["must be blank"], p.errors[:karma]
    p.karma = nil
    assert p.valid?
  end

  def test_validates_absence_of_for_ruby_class_with_custom_reader
    CustomReader.validates_absence_of :karma
    p = CustomReader.new
    p[:karma] = "excellent"
    assert p.invalid?
    assert_equal ["must be blank"], p.errors[:karma]
    p[:karma] = ""
    assert p.valid?
  end
end