Skip to content

Commit 2591d96

Browse files
andrykonchineregon
authored andcommitted
Fix Rational() and arguments type convertion
1 parent 3ad823d commit 2591d96

1 file changed

Lines changed: 31 additions & 2 deletions

File tree

core/kernel/Rational_spec.rb

Lines changed: 31 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -85,17 +85,46 @@
8585
end
8686
end
8787

88+
context "when passed neither a Numeric nor a String" do
89+
it "converts to Rational with #to_r method" do
90+
obj = Object.new
91+
def obj.to_r; 1/2r; end
92+
93+
Rational(obj).should == 1/2r
94+
end
95+
96+
it "tries to convert to Integer with #to_int method if it does not respond to #to_r" do
97+
obj = Object.new
98+
def obj.to_int; 1; end
99+
100+
Rational(obj).should == 1r
101+
end
102+
103+
it "raises TypeError if it neither responds to #to_r nor #to_int method" do
104+
-> { Rational([]) }.should raise_error(TypeError, "can't convert Array into Rational")
105+
-> { Rational({}) }.should raise_error(TypeError, "can't convert Hash into Rational")
106+
-> { Rational(nil) }.should raise_error(TypeError, "can't convert nil into Rational")
107+
end
108+
109+
it "raises TypeError if #to_r does not return Rational" do
110+
obj = Object.new
111+
def obj.to_r; []; end
112+
113+
-> { Rational(obj) }.should raise_error(TypeError, "can't convert Object to Rational (Object#to_r gives Array)")
114+
end
115+
end
116+
88117
it "raises a ZeroDivisionError if the second argument is 0" do
89118
-> { Rational(1, 0) }.should raise_error(ZeroDivisionError, "divided by 0")
90119
-> { Rational(1, 0.0) }.should raise_error(ZeroDivisionError, "divided by 0")
91120
end
92121

93122
it "raises a TypeError if the first argument is nil" do
94-
-> { Rational(nil) }.should raise_error(TypeError)
123+
-> { Rational(nil) }.should raise_error(TypeError, "can't convert nil into Rational")
95124
end
96125

97126
it "raises a TypeError if the second argument is nil" do
98-
-> { Rational(1, nil) }.should raise_error(TypeError)
127+
-> { Rational(1, nil) }.should raise_error(TypeError, "can't convert nil into Rational")
99128
end
100129

101130
it "raises a TypeError if the first argument is a Symbol" do

0 commit comments

Comments
 (0)