Skip to content

Instantly share code, notes, and snippets.

@jaynetics
Created September 26, 2022 10:30
Show Gist options
  • Select an option

  • Save jaynetics/2cede355eaf3c753bc5ea22ca236d17f to your computer and use it in GitHub Desktop.

Select an option

Save jaynetics/2cede355eaf3c753bc5ea22ca236d17f to your computer and use it in GitHub Desktop.
find broken factory_bot factories that don't work or create excessive records
FactoryBot.factories.each do |factory|
name = factory.names.count == 1 ? factory.names.first : fail
klass = factory.build_class
next unless ActiveRecord::Base.in?(klass.ancestors)
RSpec.describe "factory :#{name}" do
it "creates a single #{klass} and no insane number of other records" do
record_counts = -> do
ActiveRecord::Base.descendants.to_h { |c| [c.name.to_sym, (c.count rescue 0)] }
end
old_counts = record_counts.call
expect { create(name) }.to change { klass.count }.by(1)
new_counts = record_counts.call
added = new_counts.values.sum(0) - old_counts.values.sum(0)
expect(added).to be < 10,
"expected less than 10 added records, got #{added}: "\
"#{new_counts.to_h { |k, v| [k, v - (old_counts[k] || 0)] }.reject { |k, v| v == 0 }}"
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment