mirror of
https://github.com/thoughtbot/factory_bot.git
synced 2022-11-09 11:43:51 -05:00
#7 - class instances and names are now largely interchangeable
This commit is contained in:
parent
b4a5ab0eb8
commit
a5faf19392
3 changed files with 50 additions and 4 deletions
|
@ -61,12 +61,12 @@ class Factory
|
|||
end
|
||||
|
||||
def build_class #:nodoc:
|
||||
@build_class ||= @options[:class] || factory_name.to_s.classify.constantize
|
||||
@build_class ||= class_for(@options[:class] || factory_name)
|
||||
end
|
||||
|
||||
def initialize (name, options = {}) #:nodoc:
|
||||
options.assert_valid_keys(:class)
|
||||
@factory_name = name.to_sym
|
||||
@factory_name = factory_name_for(name)
|
||||
@options = options
|
||||
|
||||
@static_attributes = {}
|
||||
|
@ -244,4 +244,20 @@ class Factory
|
|||
instance
|
||||
end
|
||||
|
||||
def class_for (class_or_to_s)
|
||||
if class_or_to_s.respond_to?(:to_sym)
|
||||
class_or_to_s.to_s.classify.constantize
|
||||
else
|
||||
class_or_to_s
|
||||
end
|
||||
end
|
||||
|
||||
def factory_name_for (class_or_to_s)
|
||||
if class_or_to_s.respond_to?(:to_sym)
|
||||
class_or_to_s.to_sym
|
||||
else
|
||||
class_or_to_s.to_s.underscore.to_sym
|
||||
end
|
||||
end
|
||||
|
||||
end
|
||||
|
|
|
@ -269,6 +269,36 @@ class FactoryTest < Test::Unit::TestCase
|
|||
|
||||
end
|
||||
|
||||
context "when defined with a class instead of a name" do
|
||||
|
||||
setup do
|
||||
@class = ArgumentError
|
||||
@name = :argument_error
|
||||
@factory = Factory.new(@class)
|
||||
end
|
||||
|
||||
should "guess the name from the class" do
|
||||
assert_equal @name, @factory.factory_name
|
||||
end
|
||||
|
||||
should "use the class as the build class" do
|
||||
assert_equal @class, @factory.build_class
|
||||
end
|
||||
|
||||
end
|
||||
context "when defined with a custom class name" do
|
||||
|
||||
setup do
|
||||
@class = ArgumentError
|
||||
@factory = Factory.new(:author, :class => :argument_error)
|
||||
end
|
||||
|
||||
should "use the specified class as the build class" do
|
||||
assert_equal @class, @factory.build_class
|
||||
end
|
||||
|
||||
end
|
||||
|
||||
context "with some attributes added" do
|
||||
|
||||
setup do
|
||||
|
|
|
@ -3,14 +3,14 @@ require(File.join(File.dirname(__FILE__), 'test_helper'))
|
|||
class IntegrationTest < Test::Unit::TestCase
|
||||
|
||||
def setup
|
||||
Factory.define :user do |f|
|
||||
Factory.define :user, :class => 'user' do |f|
|
||||
f.first_name 'Jimi'
|
||||
f.last_name 'Hendrix'
|
||||
f.admin false
|
||||
f.email {|a| "#{a.first_name}.#{a.last_name}@example.com".downcase }
|
||||
end
|
||||
|
||||
Factory.define 'post' do |f|
|
||||
Factory.define Post do |f|
|
||||
f.name 'Test Post'
|
||||
f.association :author, :factory => :user
|
||||
end
|
||||
|
|
Loading…
Reference in a new issue