-
-
Notifications
You must be signed in to change notification settings - Fork 389
/
Copy pathsafe_navigator_spec.rb
147 lines (115 loc) · 2.55 KB
/
safe_navigator_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
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
require_relative '../spec_helper'
describe "Safe navigator" do
it "requires a method name to be provided" do
-> { eval("obj&. {}") }.should raise_error(SyntaxError)
end
context "when context is nil" do
it "always returns nil" do
nil&.unknown.should == nil
[][10]&.unknown.should == nil
end
it "can be chained" do
nil&.one&.two&.three.should == nil
end
it "doesn't evaluate arguments" do
obj = Object.new
obj.should_not_receive(:m)
nil&.unknown(obj.m) { obj.m }
end
end
context "when context is false" do
it "calls the method" do
false&.to_s.should == "false"
-> { false&.unknown }.should raise_error(NoMethodError)
end
end
context "when context is truthy" do
it "calls the method" do
1&.to_s.should == "1"
-> { 1&.unknown }.should raise_error(NoMethodError)
end
end
it "takes a list of arguments" do
[1,2,3]&.first(2).should == [1,2]
end
it "takes a block" do
[1,2]&.map { |i| i * 2 }.should == [2, 4]
end
it "allows assignment methods" do
klass = Class.new do
attr_reader :foo
def foo=(val)
@foo = val
42
end
end
obj = klass.new
(obj&.foo = 3).should == 3
obj.foo.should == 3
obj = nil
(obj&.foo = 3).should == nil
end
it "allows assignment operators" do
klass = Class.new do
attr_reader :m
def initialize
@m = 0
end
def m=(v)
@m = v
42
end
end
obj = klass.new
obj&.m += 3
obj.m.should == 3
obj = nil
(obj&.m += 3).should == nil
end
it "allows ||= operator" do
klass = Class.new do
attr_reader :m
def initialize
@m = false
end
def m=(v)
@m = v
42
end
end
obj = klass.new
(obj&.m ||= true).should == true
obj.m.should == true
obj = nil
(obj&.m ||= true).should == nil
obj.should == nil
end
it "allows &&= operator" do
klass = Class.new do
attr_accessor :m
def initialize
@m = true
end
end
obj = klass.new
(obj&.m &&= false).should == false
obj.m.should == false
obj = nil
(obj&.m &&= false).should == nil
obj.should == nil
end
it "does not call the operator method lazily with an assignment operator" do
klass = Class.new do
attr_writer :foo
def foo
nil
end
end
obj = klass.new
-> {
obj&.foo += 3
}.should raise_error(NoMethodError) { |e|
e.name.should == :+
}
end
end