/
notify_spec.rb
124 lines (103 loc) · 2.73 KB
/
notify_spec.rb
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
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
require File.dirname(__FILE__) + '/spec_helper.rb'
require 'ruby-plc/etc/notify.rb'
class NotifyTestEmpty
extend Notify
end
class NotifyTestOne
extend Notify
notify :one
end
class NotifyTestOneWithHandler
extend Notify
notify :one
def handle_notify_error(ex)
throw RuntimeError.new('Notified')
end
end
class NotifyTestOneTwo
extend Notify
notify :one
notify :two
end
class NotifyTestTwo
extend Notify
notify :one, :two
end
describe Notify do
before(:each) do
@empty = NotifyTestEmpty.new
@one = NotifyTestOne.new
@one_handler = NotifyTestOneWithHandler.new
@one_two = NotifyTestOneTwo.new
@two = NotifyTestTwo.new
end
it "should support the on_one method for adding listeners" do
@one.on_one do
end
end
it "should support the notify_one methos for informing listeners" do
@one.notify_one
end
it "should call the callback method when notify is issued" do
tmp = nil
@one.on_one do
tmp = true
end
@one.notify_one
tmp.should be_true
end
it "should not call the callback in the wrong notification" do
@one_two.on_two do
violated 'This should not happen'
end
@one_two.notify_one
end
it "should support more than one listener" do
@count = 0
[1, 2, 5, 6].each do |x|
@one.on_one { @count += x }
end
@one.notify_one
@count.should equal(14)
end
it "should not misbehave if an exception is thrown by a listener" do
@test = nil
@one.on_one { throw RuntimeError.new('Boom!') }
@one.on_one { @test = true }
lambda { @one.notify_one }.should_not raise_error(RuntimeError, /Boom/)
@test.should be_true
end
it "should not misbehave if an exception is thrown by a listener, even errors" do
@test = nil
@one.on_one { @test.call_undefined_method }
@one.on_one { @test = true }
lambda { @one.notify_one }.should_not raise_error(RuntimeError, /Boom/)
@test.should be_true
end
it "should call handle_notify_error if available" do
@one_handler.on_one { throw 'BOOM' }
lambda { @one_handler.notify_one }.should raise_error(Exception, /Notified/)
end
it 'should allow two or more notify declarations on one line' do
@two.on_one { puts 'test' }
@two.on_two { puts 'test' }
end
it 'should pass arguments to notification messages' do
@one.on_one do |a, b|
a.should be_true
b.should be_true
end
@one.notify_one true, true
end
it 'should only call a callback once even if registered more times' do
counter = 0
p = Proc.new { counter += 1 }
(1..10).each do
# TODO: This doesnt work - will it work on ruby 1.9?
# @one.on_one { counter += 1 }
@one.on_one(&p)
end
@one.notify_one
counter.should be(1)
end
end