aboutsummaryrefslogtreecommitdiffstats
path: root/activemodel/test/cases/validations/exclusion_validation_test.rb
blob: 72a383f128bf5d1f8315d16a1f691cf3ca40d7b6 (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
# encoding: utf-8
require 'cases/helper'

require 'models/topic'
require 'models/person'

class ExclusionValidationTest < ActiveModel::TestCase

  def teardown
    Topic.reset_callbacks(:validate)
  end

  def test_validates_exclusion_of
    Topic.validates_exclusion_of( :title, :in => %w( abe monkey ) )

    assert Topic.new("title" => "something", "content" => "abc").valid?
    assert Topic.new("title" => "monkey", "content" => "abc").invalid?
  end

  def test_validates_exclusion_of_with_formatted_message
    Topic.validates_exclusion_of( :title, :in => %w( abe monkey ), :message => "option %{value} is restricted" )

    assert Topic.new("title" => "something", "content" => "abc")

    t = Topic.new("title" => "monkey")
    assert t.invalid?
    assert t.errors[:title].any?
    assert_equal ["option monkey is restricted"], t.errors[:title]
  end

  def test_validates_exclusion_of_for_ruby_class
    Person.validates_exclusion_of :karma, :in => %w( abe monkey )

    p = Person.new
    p.karma = "abe"
    assert p.invalid?

    assert_equal ["is reserved"], p.errors[:karma]

    p.karma = "Lifo"
    assert p.valid?
  ensure
    Person.reset_callbacks(:validate)
  end

  def test_validates_exclusion_of_with_lambda
    Topic.validates_exclusion_of :title, :in => lambda{ |topic| topic.author_name == "sikachu" ? %w( monkey elephant ) : %w( abe wasabi ) }

    p = Topic.new
    p.title = "elephant"
    p.author_name = "sikachu"
    assert p.invalid?

    p.title = "wasabi"
    assert p.valid?
  end
end