From: Nathaniel Talbott Date: 2003-08-02T17:59:29+09:00 Subject: Re: Test::Unit leaving phanthom objects in ObjectSpace? james_b [mailto:james_b@neurogami.com] wrote: > Nathaniel Talbott wrote: > > If that's a bit too > > messy, your solution of calling ObjectSpace#garbage_collect in > > teardown is probably the next best thing. Another solution would be to > > pass the ObjectSpace in to the code that uses it - that way you can > > use a mock when testing that code and not be dependent on the GC at > > all. > > The code being tested loops over ObjectSapce. Can you do something like this: def my_object_space_code(object_space=ObjectSpace) object_space.each_object(SomeClass) do |object| ... do stuff ... end end ... def test_my_object_space_code object_space = Object.new def object_space.each_object(klass, &block) [Thing1.new, Thing2.new].each(&block) end my_object_space_code(object_space) ... make assertions ... end I've done exactly that and found it to be much more deterministic than trying to test ObjectSpace directly. If I assume that ObjectSpace itself works, which I do, it makes my life much simpler to completely remove it from the equation when testing. > Oddly, calling > ObjectSpace#garbage_collect in that code right before iterating didn't > help. My guess is that doing that didn't leave enough time between when you asked for collection and when you wanted that collection to have happened. TestCase#teardown for the last test happens a lot earlier than a call in the current test. This is why using ObjectSpace in the test itself would worry me... what's the magic timing? Could some seemingly unrelated change (in hardware, in OS, etc.) cause the test to start failing all of the sudden when the code still works just fine? > Is there a way to ask an object if nothing refers to it? My guess is no... usually that would be a contradiction in terms - by the very fact that you can ask, "Does anything refer to you?", the answer is "Yes." The weird case of ObjectSpace (and I'm guessing WeakRefs, although I haven't used them at all) is just, well, weird; perhaps someone more familiar with Ruby internals can give a more satisfactory answer here. HTH, Nathaniel <:((><