aboutsummaryrefslogtreecommitdiffstats
path: root/activerecord/test/cases/validations/presence_validation_test.rb
blob: 6f8ad06ab667fa5541bb89ee318f2562df434f70 (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
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
require "cases/helper"
require 'models/man'
require 'models/face'
require 'models/interest'
require 'models/speedometer'
require 'models/dashboard'

class PresenceValidationTest < ActiveRecord::TestCase
  class Boy < Man; end

  repair_validations(Boy)

  def test_validates_presence_of_non_association
    Boy.validates_presence_of(:name)
    b = Boy.new
    assert b.invalid?

    b.name = "Alex"
    assert b.valid?
  end

  def test_validates_presence_of_has_one
    Boy.validates_presence_of(:face)
    b = Boy.new
    assert b.invalid?, "should not be valid if has_one association missing"
    assert_equal 1, b.errors[:face].size, "validates_presence_of should only add one error"
  end

  def test_validates_presence_of_has_one_marked_for_destruction
    Boy.validates_presence_of(:face)
    b = Boy.new
    f = Face.new
    b.face = f
    assert b.valid?

    f.mark_for_destruction
    assert b.invalid?
  end

  def test_validates_presence_of_has_many_marked_for_destruction
    Boy.validates_presence_of(:interests)
    b = Boy.new
    b.interests << [i1 = Interest.new, i2 = Interest.new]
    assert b.valid?

    i1.mark_for_destruction
    assert b.valid?

    i2.mark_for_destruction
    assert b.invalid?
  end

  def test_validates_presence_doesnt_convert_to_array
    speedometer = Class.new(Speedometer)
    speedometer.validates_presence_of :dashboard

    dash = Dashboard.new

    # dashboard has to_a method
    def dash.to_a; ['(/)', '(\)']; end

    s = speedometer.new
    s.dashboard = dash

    assert_nothing_raised { s.valid? }
  end

  def test_does_not_validate_presence_of_if_parent_record_is_validate_false
    repair_validations(Interest) do
      Interest.validates_presence_of(:topic)
      interest = Interest.new
      interest.save!(validate: false)
      assert interest.persisted?

      man = Man.new(interest_ids: [interest.id])
      man.save!

      assert_equal man.interests.size, 1
      assert interest.valid?
      assert man.valid?
    end
  end
end