Skip to content

Instantly share code, notes, and snippets.

@slauwers
Last active August 29, 2015 14:07
Show Gist options
  • Save slauwers/f5c769cc2a6902e9d3b2 to your computer and use it in GitHub Desktop.
Save slauwers/f5c769cc2a6902e9d3b2 to your computer and use it in GitHub Desktop.
Helper class to identify which classes are leaking in unit tests
before(:all) do
@stats = OStats.new filters: ['Grape'], suppress_nodelta: true
@stats.collect!
end
after(:all) do
@stats.collect!
@stats.display
end
Grape::Route 87 delta 71
Grape::Util::HashStack 68 delta 28
Grape::Endpoint 56 delta 29
Grape::Request 1 delta 1
Grape::Cookies 1 delta 1
# Based on http://johansorensen.com/articles/finding-leaking-ruby-objects.html
# and https://groups.google.com/d/msg/comp.lang.ruby/KvUdmQSsf-U/Vn-yDUoWt2EJ
class OStats
def initialize options
@filters = (options.delete :filters) || ['']
@suppress_nodelta = options.delete :suppress_nodelta
@stats = Array.new
end
def collect!
stats = Hash.new(0)
ObjectSpace.each_object do |o|
@filters.each do |f|
stats[o.class] += 1 if o.class.name.start_with? f
end
end
@stats << stats
end
def display
@stats[-1].sort {|(k1,v1),(k2,v2)| v2 <=> v1}.each do |k,v|
delta = ((v - @stats[-2][k]) unless @stats[-2].nil?) || 0
if !@suppress_nodelta or delta != 0
printf "%-60s %10d", k, v
if !@suppress_nodelta or delta != 0
printf " delta %10d", delta
end
puts
end
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment