Skip to content

Commit 366722d

Browse files
nobueregon
authored andcommitted
Add Integer.try_convert [Feature #15211]
1 parent 12cb80e commit 366722d

File tree

1 file changed

+40
-0
lines changed

1 file changed

+40
-0
lines changed

core/integer/try_convert_spec.rb

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
require_relative '../../spec_helper'
2+
require_relative 'fixtures/classes'
3+
4+
ruby_version_is "3.1" do
5+
describe "Integer.try_convert" do
6+
it "returns the argument if it's an Integer" do
7+
x = 42
8+
Integer.try_convert(x).should equal(x)
9+
end
10+
11+
it "returns nil when the argument does not respond to #to_int" do
12+
Integer.try_convert(Object.new).should be_nil
13+
end
14+
15+
it "sends #to_int to the argument and returns the result if it's nil" do
16+
obj = mock("to_int")
17+
obj.should_receive(:to_int).and_return(nil)
18+
Integer.try_convert(obj).should be_nil
19+
end
20+
21+
it "sends #to_int to the argument and returns the result if it's an Integer" do
22+
x = 234
23+
obj = mock("to_int")
24+
obj.should_receive(:to_int).and_return(x)
25+
Integer.try_convert(obj).should equal(x)
26+
end
27+
28+
it "sends #to_int to the argument and raises TypeError if it's not a kind of Integer" do
29+
obj = mock("to_int")
30+
obj.should_receive(:to_int).and_return(Object.new)
31+
-> { Integer.try_convert obj }.should raise_error(TypeError)
32+
end
33+
34+
it "does not rescue exceptions raised by #to_int" do
35+
obj = mock("to_int")
36+
obj.should_receive(:to_int).and_raise(RuntimeError)
37+
-> { Integer.try_convert obj }.should raise_error(RuntimeError)
38+
end
39+
end
40+
end

0 commit comments

Comments
 (0)