diff --git a/core/data/deconstruct_keys_spec.rb b/core/data/deconstruct_keys_spec.rb index 5cae4cbd68..df08652f24 100644 --- a/core/data/deconstruct_keys_spec.rb +++ b/core/data/deconstruct_keys_spec.rb @@ -84,6 +84,28 @@ d.deconstruct_keys(nil).should == {x: 1, y: 2} end + it "tries to convert a key with #to_int if index is not a String nor a Symbol, but responds to #to_int" do + klass = Data.define(:x, :y) + d = klass.new(1, 2) + + key = mock("to_int") + key.should_receive(:to_int).and_return(1) + + d.deconstruct_keys([key]).should == { key => 2 } + end + + it "raises a TypeError if the conversion with #to_int does not return an Integer" do + klass = Data.define(:x, :y) + d = klass.new(1, 2) + + key = mock("to_int") + key.should_receive(:to_int).and_return("not an Integer") + + -> { + d.deconstruct_keys([key]) + }.should raise_error(TypeError, /can't convert MockObject to Integer/) + end + it "raises TypeError if index is not a String, a Symbol and not convertible to Integer " do klass = Data.define(:x, :y) d = klass.new(1, 2) diff --git a/core/struct/deconstruct_keys_spec.rb b/core/struct/deconstruct_keys_spec.rb index 602403d183..1639a1abbb 100644 --- a/core/struct/deconstruct_keys_spec.rb +++ b/core/struct/deconstruct_keys_spec.rb @@ -80,6 +80,28 @@ obj.deconstruct_keys(nil).should == {x: 1, y: 2} end + it "tries to convert a key with #to_int if index is not a String nor a Symbol, but responds to #to_int" do + struct = Struct.new(:x, :y) + s = struct.new(1, 2) + + key = mock("to_int") + key.should_receive(:to_int).and_return(1) + + s.deconstruct_keys([key]).should == { key => 2 } + end + + it "raises a TypeError if the conversion with #to_int does not return an Integer" do + struct = Struct.new(:x, :y) + s = struct.new(1, 2) + + key = mock("to_int") + key.should_receive(:to_int).and_return("not an Integer") + + -> { + s.deconstruct_keys([key]) + }.should raise_error(TypeError, /can't convert MockObject to Integer/) + end + it "raises TypeError if index is not a String, a Symbol and not convertible to Integer" do struct = Struct.new(:x, :y) s = struct.new(1, 2)