Created
October 12, 2012 09:29
-
-
Save txus/3878360 to your computer and use it in GitHub Desktop.
Factory Police: detect unused factories in your tests
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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