Skip to content

Instantly share code, notes, and snippets.

@txus
Created October 12, 2012 09:29
Show Gist options
  • Save txus/3878360 to your computer and use it in GitHub Desktop.
Save txus/3878360 to your computer and use it in GitHub Desktop.
Factory Police: detect unused factories in your tests
# spec/spec_helper.rb
config.after(:all, db: true) do
puts
puts
FactoryPolice.report
end
# spec/support/factory_police.rb
module FactoryGirl
class << self
alias_method :__create__, :create
def create(*args)
FactoryPolice.new __create__(*args)
end
end
end
class FactoryPolice < BasicObject
@@proxies = []
def self.report
@@proxies.each(&:report)
end
def initialize(model)
@created_at = caller[3].split(':').take(2).join(':')
@model = model
@@proxies << self
end
def report
if useless?
puts "[ #{@created_at} ] - #{@model} is never interacted with directly"
end
end
def method_missing(m, *args, &block)
calls[m] += 1
@model.send m, *args, &block
end
private
def useless?
(@calls.keys - ignore).empty?
end
def ignore
[:puts, :caller]
end
def calls
@calls ||= ::Hash.new { |h, k| h[k] = 0 }
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment