#1 - automatically load factory definitions from standard locations

This commit is contained in:
Joe Ferris 2008-08-20 10:20:41 -04:00
parent 428c0b537d
commit 30a877ed15
3 changed files with 35 additions and 0 deletions

View File

@ -12,3 +12,5 @@ require 'factory_girl/aliases'
def Factory (name, attrs = {})
Factory.create(name, attrs)
end
Factory.find_definitions

View File

@ -3,6 +3,13 @@ class Factory
cattr_accessor :factories #:nodoc:
self.factories = {}
# An Array of strings specifying locations that should be searched for
# factory definitions. By default, factory_girl will attempt to require
# "factories," "test/factories," and "spec/factories." Only the first
# existing file will be loaded.
cattr_accessor :definition_file_paths
self.definition_file_paths = %w(factories test/factories spec/factories)
attr_reader :factory_name
# Defines a new factory that can be used by the build strategies (create and
@ -173,6 +180,16 @@ class Factory
factory_by_name(name).create(attrs)
end
def find_definitions #:nodoc:
definition_file_paths.each do |path|
begin
require(path)
break
rescue LoadError
end
end
end
private
def factory_by_name (name)

View File

@ -415,4 +415,20 @@ class FactoryTest < Test::Unit::TestCase
end
Factory.definition_file_paths.each do |file|
should "automatically load definitions from #{file}.rb" do
Factory.stubs(:require).raises(LoadError)
Factory.expects(:require).with(file)
Factory.find_definitions
end
end
should "only load the first set of factories detected" do
first, second, third = Factory.definition_file_paths
Factory.expects(:require).with(first).raises(LoadError)
Factory.expects(:require).with(second)
Factory.expects(:require).with(third).never
Factory.find_definitions
end
end