|
85 | 85 | end |
86 | 86 | end |
87 | 87 |
|
| 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 | + |
88 | 117 | it "raises a ZeroDivisionError if the second argument is 0" do |
89 | 118 | -> { Rational(1, 0) }.should raise_error(ZeroDivisionError, "divided by 0") |
90 | 119 | -> { Rational(1, 0.0) }.should raise_error(ZeroDivisionError, "divided by 0") |
91 | 120 | end |
92 | 121 |
|
93 | 122 | 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") |
95 | 124 | end |
96 | 125 |
|
97 | 126 | 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") |
99 | 128 | end |
100 | 129 |
|
101 | 130 | it "raises a TypeError if the first argument is a Symbol" do |
|
0 commit comments