aboutsummaryrefslogtreecommitdiffstats
path: root/activemodel/test/cases/model_test.rb
blob: ba87cd1506245534003f1747ec1712357e54c10a (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
require "cases/helper"

class ModelTest < ActiveModel::TestCase
  include ActiveModel::Lint::Tests

  module DefaultValue
    def self.included(klass)
      klass.class_eval { attr_accessor :hello }
    end

    def initialize(*args)
      @attr ||= "default value"
      super
    end
  end

  class BasicModel
    include DefaultValue
    include ActiveModel::Model
    attr_accessor :attr
  end

  class BasicModelWithReversedMixins
    include ActiveModel::Model
    include DefaultValue
    attr_accessor :attr
  end

  class SimpleModel
    include ActiveModel::Model
    attr_accessor :attr
  end

  def setup
    @model = BasicModel.new
  end

  def test_initialize_with_params
    object = BasicModel.new(attr: "value")
    assert_equal "value", object.attr
  end

  def test_initialize_with_params_and_mixins_reversed
    object = BasicModelWithReversedMixins.new(attr: "value")
    assert_equal "value", object.attr
  end

  def test_initialize_with_nil_or_empty_hash_params_does_not_explode
    assert_nothing_raised do
      BasicModel.new()
      BasicModel.new(nil)
      BasicModel.new({})
      SimpleModel.new(attr: "value")
    end
  end

  def test_persisted_is_always_false
    object = BasicModel.new(attr: "value")
    assert object.persisted? == false
  end

  def test_mixin_inclusion_chain
    object = BasicModel.new
    assert_equal "default value", object.attr
  end

  def test_mixin_initializer_when_args_exist
    object = BasicModel.new(hello: "world")
    assert_equal "world", object.hello
  end

  def test_mixin_initializer_when_args_dont_exist
    assert_raises(ActiveModel::UnknownAttributeError) do
      SimpleModel.new(hello: "world")
    end
  end
end