Skip to content

Instantly share code, notes, and snippets.

@benoittgt
Created March 9, 2018 15:04
Show Gist options
  • Save benoittgt/a13ad810f9fd21963fb8be9751ff7956 to your computer and use it in GitHub Desktop.
Save benoittgt/a13ad810f9fd21963fb8be9751ff7956 to your computer and use it in GitHub Desktop.
find where data are leaking with rspec and active record
RSpec.configure do |config|
config.before(:suite) do
FactoryBot.find_definitions if FactoryBot.factories.count == 0
DatabaseCleaner[:active_record].clean_with(:transaction)
end
config.around(:each) do |example|
unless User.count.zero?
# we will output to current terminal but also into a file in tmp
open('tmp/leaky.txt', 'a') { |f|
f << "Location is: #{example.location} with #{User.count} and ids: #{User.ids}\n"
}
p example.location
puts "Leak with #{User.count} and ids: #{User.ids}"
end
DatabaseCleaner.cleaning do
example.run
end
DataStore.clear
end
end
@benoittgt
Copy link
Author

  Zeitwerk::Loader.eager_load_all; nil
  models = ApplicationRecord.descendants
  puts '๐Ÿ™' * (`tput cols`.to_i / 2)
  puts "Monitoring #{models.join(', ')}"
  puts '๐Ÿ™' * (`tput cols`.to_i / 2)

  config.around(:each) do |example|
    example.run

    positive_counts = 0
    t = Thread.new do
      positive_counts = models.select { |model| model.count.positive? }.map { |model| "#{model.name} has #{model.count} records" }
    end
    t.join

    if positive_counts.any?
      open('tmp/leaky.txt', 'a') { |f|
        f << "Location is: #{example.location} with #{positive_counts.join(', ')} \n"
      }
      puts "Location is: #{example.location} with #{positive_counts.join(', ')} \n"
    end

  end

wip

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment