1 require 'abstract_unit'
2 require 'fixtures/topic'
3 require 'fixtures/developer'
4 require 'fixtures/reply'
6 class Topic; def after_find() end end
7 class Developer; def after_find() end end
8 class SpecialDeveloper < Developer; end
10 class TopicManualObserver
13 attr_reader :action, :object, :callbacks
16 Topic.add_observer(self)
20 def update(callback_method, object)
21 @callbacks << { "callback_method" => callback_method, "object" => object }
24 def has_been_notified?
29 class TopicaObserver < ActiveRecord::Observer
39 class TopicObserver < ActiveRecord::Observer
47 class MultiObserver < ActiveRecord::Observer
50 def self.observed_class() [ Topic, Developer ] end
52 cattr_reader :last_inherited
53 @@last_inherited = nil
55 def observed_class_inherited_with_testing(subclass)
56 observed_class_inherited_without_testing(subclass)
57 @@last_inherited = subclass
60 alias_method_chain :observed_class_inherited, :testing
62 def after_find(record)
67 class LifecycleTest < Test::Unit::TestCase
68 fixtures :topics, :developers
70 def test_before_destroy
71 assert_equal 2, Topic.count
73 assert_equal 0, Topic.count
77 ActiveRecord::Base.observers = :topic_manual_observer
78 ActiveRecord::Base.instantiate_observers
84 assert TopicManualObserver.instance.has_been_notified?
85 assert_equal :after_save, TopicManualObserver.instance.callbacks.last["callback_method"]
88 def test_observer_update_on_save
89 ActiveRecord::Base.observers = TopicManualObserver
90 ActiveRecord::Base.instantiate_observers
93 assert TopicManualObserver.instance.has_been_notified?
94 assert_equal :after_find, TopicManualObserver.instance.callbacks.first["callback_method"]
97 def test_auto_observer
98 topic_observer = TopicaObserver.instance
100 topic = Topic.find(1)
101 assert_equal topic.title, topic_observer.topic.title
104 def test_inferred_auto_observer
105 topic_observer = TopicObserver.instance
107 topic = Topic.find(1)
108 assert_equal topic.title, topic_observer.topic.title
111 def test_observing_two_classes
112 multi_observer = MultiObserver.instance
114 topic = Topic.find(1)
115 assert_equal topic.title, multi_observer.record.title
117 developer = Developer.find(1)
118 assert_equal developer.name, multi_observer.record.name
121 def test_observing_subclasses
122 multi_observer = MultiObserver.instance
124 developer = SpecialDeveloper.find(1)
125 assert_equal developer.name, multi_observer.record.name
127 klass = Class.new(Developer)
128 assert_equal klass, multi_observer.last_inherited
130 developer = klass.find(1)
131 assert_equal developer.name, multi_observer.record.name
134 def test_invalid_observer
135 assert_raise(ArgumentError) { Topic.observers = Object.new; Topic.instantiate_observers }