1require_relative '../../spec_helper'
2require_relative 'fixtures/classes'
3
4describe "Class.inherited" do
5
6  before :each do
7    ScratchPad.record nil
8  end
9
10  it "is invoked with the child Class when self is subclassed" do
11    begin
12      top = Class.new do
13        def self.inherited(cls)
14          $child_class = cls
15        end
16      end
17
18      child = Class.new(top)
19      $child_class.should == child
20
21      other_child = Class.new(top)
22      $child_class.should == other_child
23    ensure
24      $child_class = nil
25    end
26  end
27
28  it "is invoked only once per subclass" do
29    expected = [
30      [CoreClassSpecs::Inherited::A, CoreClassSpecs::Inherited::B],
31      [CoreClassSpecs::Inherited::B, CoreClassSpecs::Inherited::C],
32    ]
33
34    CoreClassSpecs::Inherited::A::SUBCLASSES.should == expected
35  end
36
37  it "is called when marked as a private class method" do
38    a = Class.new do
39      def self.inherited(klass)
40        ScratchPad.record klass
41      end
42    end
43    a.private_class_method :inherited
44    ScratchPad.recorded.should == nil
45    b = Class.new(a)
46    ScratchPad.recorded.should == b
47  end
48
49  it "is called when marked as a protected class method" do
50    a = Class.new
51    class << a
52      def inherited(klass)
53        ScratchPad.record klass
54      end
55      protected :inherited
56    end
57    ScratchPad.recorded.should == nil
58    b = Class.new(a)
59    ScratchPad.recorded.should == b
60  end
61
62  it "is called when marked as a public class method" do
63    a = Class.new do
64      def self.inherited(klass)
65        ScratchPad.record klass
66      end
67    end
68    a.public_class_method :inherited
69    ScratchPad.recorded.should == nil
70    b = Class.new(a)
71    ScratchPad.recorded.should == b
72  end
73
74  it "is called by super from a method provided by an included module" do
75    ScratchPad.recorded.should == nil
76    e = Class.new(CoreClassSpecs::F)
77    ScratchPad.recorded.should == e
78  end
79
80  it "is called by super even when marked as a private class method" do
81    ScratchPad.recorded.should == nil
82    CoreClassSpecs::H.private_class_method :inherited
83    i = Class.new(CoreClassSpecs::H)
84    ScratchPad.recorded.should == i
85  end
86
87  it "will be invoked by child class regardless of visibility" do
88    top = Class.new do
89      class << self
90        def inherited(cls); end
91      end
92    end
93
94    class << top; private :inherited; end
95    lambda { Class.new(top) }.should_not raise_error
96
97    class << top; protected :inherited; end
98    lambda { Class.new(top) }.should_not raise_error
99  end
100
101end
102