aboutsummaryrefslogtreecommitdiffstats
path: root/activesupport/test/core_ext/class/attribute_accessor_test.rb
blob: 0d5f39a72b4241b27c5155f754970d7d324d8d48 (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
require 'abstract_unit'
require 'active_support/core_ext/class/attribute_accessors'

class ClassAttributeAccessorTest < ActiveSupport::TestCase
  def setup
    @class = Class.new do
      cattr_accessor :foo
      cattr_accessor :bar,  :instance_writer   => false
      cattr_reader   :shaq, :instance_reader   => false
      cattr_accessor :camp, :instance_accessor => false
    end
    @object = @class.new
  end

  def test_should_use_mattr_default
    assert_nil @class.foo
    assert_nil @object.foo
  end

  def test_should_set_mattr_value
    @class.foo = :test
    assert_equal :test, @object.foo

    @object.foo = :test2
    assert_equal :test2, @class.foo
  end

  def test_should_not_create_instance_writer
    assert_respond_to @class, :foo
    assert_respond_to @class, :foo=
    assert_respond_to @object, :bar
    assert !@object.respond_to?(:bar=)
  end

  def test_should_not_create_instance_reader
    assert_respond_to @class, :shaq
    assert !@object.respond_to?(:shaq)
  end

  def test_should_not_create_instance_accessors
    assert_respond_to @class, :camp
    assert !@object.respond_to?(:camp)
    assert !@object.respond_to?(:camp=)
  end

  def test_should_raise_name_error_if_attribute_name_is_invalid
    exception = assert_raises NameError do
      Class.new do
        cattr_reader "1nvalid"
      end
    end
    assert_equal "invalid class attribute name: 1nvalid", exception.message

    exception = assert_raises NameError do
      Class.new do
        cattr_writer "1nvalid"
      end
    end
    assert_equal "invalid class attribute name: 1nvalid", exception.message
  end
end