diff options
| author | Jean Boussier <jean.boussier@gmail.com> | 2025-11-28 16:17:06 +0100 |
|---|---|---|
| committer | Jean Boussier <jean.boussier@gmail.com> | 2025-11-28 18:34:59 +0100 |
| commit | 191bfcb9c505ba3f5771f7ac67d6131aeb6b6837 (patch) | |
| tree | 908014971b70e6994d367f9966bdda363347081c /spec/ruby | |
| parent | 8eaefd93951143661b1f515a8c9cda12263d2b56 (diff) | |
Define Kernel#instance_variables_to_inspect
[Bug #21718]
Otherwise objects that don't define it, but define a fairly liberal
`method_missing` method will run into errors that are hard to understand:
```ruby
class Foo
def method_missing(name, ...)
name
end
end
p Foo.new.inspect
```
```
'Kernel#inspect': wrong argument type Symbol (expected Array) (TypeError)
from ../test.rb:7:in '<main>'
```
Diffstat (limited to 'spec/ruby')
| -rw-r--r-- | spec/ruby/core/kernel/inspect_spec.rb | 29 |
1 files changed, 29 insertions, 0 deletions
diff --git a/spec/ruby/core/kernel/inspect_spec.rb b/spec/ruby/core/kernel/inspect_spec.rb index 6ecf1e1c8c..1fa66cab98 100644 --- a/spec/ruby/core/kernel/inspect_spec.rb +++ b/spec/ruby/core/kernel/inspect_spec.rb @@ -57,5 +57,34 @@ describe "Kernel#inspect" do inspected = obj.inspect.sub(/^#<Object:0x[0-9a-f]+/, '#<Object:0x00') inspected.should == "#<Object:0x00>" end + + it "displays all instance variables if #instance_variables_to_inspect returns nil" do + obj = Object.new + obj.instance_eval do + @host = "localhost" + @user = "root" + @password = "hunter2" + end + obj.singleton_class.class_eval do + private def instance_variables_to_inspect = nil + end + + inspected = obj.inspect.sub(/^#<Object:0x[0-9a-f]+/, '#<Object:0x00') + inspected.should == %{#<Object:0x00 @host="localhost", @user="root", @password="hunter2">} + end + + it "raises an error if #instance_variables_to_inspect returns an invalid value" do + obj = Object.new + obj.instance_eval do + @host = "localhost" + @user = "root" + @password = "hunter2" + end + obj.singleton_class.class_eval do + private def instance_variables_to_inspect = {} + end + + ->{ obj.inspect }.should raise_error(TypeError, "Expected #instance_variables_to_inspect to return an Array or nil, but it returned Hash") + end end end |
