Skip to content

Instantly share code, notes, and snippets.

@frankyston
Forked from romulogomes/rails_helper.rb
Created February 27, 2024 22:35
Show Gist options
  • Save frankyston/6b26ed09e850c6b80eafb4be4cc57886 to your computer and use it in GitHub Desktop.
Save frankyston/6b26ed09e850c6b80eafb4be4cc57886 to your computer and use it in GitHub Desktop.
Factories lowest
def red(text)
"\033[31m#{text}\033[0m"
end
number_of_factories_to_analyze = 10
load_begin = Time.now
stats = {}
ActiveSupport::Notifications.subscribe("factory_bot.run_factory") do |_name, start, finish, _id, payload|
execution_time_in_seconds = finish - start
stats[payload[:name]] = stats[payload[:name]].to_f + execution_time_in_seconds
end
RSpec.configure do |config|
config.after(:suite) do
sorted_stats = stats.sort_by { |_name, execution_time| -execution_time }.take(number_of_factories_to_analyze)
slowest_sum = sorted_stats.inject(0) { |sum, stat| sum + stat.last }
total_time = Time.now - load_begin
$stdout.puts "\nTop 10 slowest factories (#{slowest_sum.round(2)} seconds, #{(slowest_sum / total_time * 100).round(2)}% of total time):"
sorted_stats.each do |name, execution_time|
$stdout.puts " #{red("#{execution_time.round(5)} seconds")} - #{name}"
end
end
end
@frankyston
Copy link
Author

O que fizemos nas factories?

1.⁠ ⁠Removemos associações desnecessárias que só eram usadas em alguns cenários.
2.⁠ ⁠Alteramos algumas criações de associações para trait’s e algumas para usar build ao invés de não mencionar como ela deve ser criada (por padrão é executado com create)
3.⁠ ⁠Associações pouco usadas removemos da factory e criamos no próprio setup do testes.

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