Base class is implied when calling .new within initialize_with

Closes #343
This commit is contained in:
Joshua Clayton 2012-04-23 22:48:33 -05:00
parent 351b04de02
commit 9907826ee5
5 changed files with 49 additions and 4 deletions

View File

@ -723,7 +723,7 @@ factory :user do
end
email
initialize_with { User.new(name) }
initialize_with { new(name) }
end
FactoryGirl.build(:user).name # Bob Hope
@ -745,6 +745,22 @@ You can override the initializer in order to:
* Use a method other than `new` to instantiate the instance
* Do crazy things like decorate the instance after it's built
When using `initialize_with`, you don't have to declare the class itself when
calling `new`; however, any other class methods you want to call will have to
be called on the class explicitly.
For example:
```ruby
factory :user do
ignore do
name { Faker::Name.name }
end
initialize_with { User.build_with_name(name) }
end
```
Custom Strategies
-----------------

View File

@ -17,7 +17,8 @@ module FactoryGirl
undef_method(method) unless method =~ /^__|initialize/
end
def initialize(build_strategy, overrides = {})
def initialize(build_class, build_strategy, overrides = {})
@build_class = build_class
@build_strategy = build_strategy
@overrides = overrides
@cached_attributes = overrides
@ -27,6 +28,8 @@ module FactoryGirl
end
end
delegate :new, to: :@build_class
def association(factory_name, overrides = {})
strategy_override = overrides.fetch(:strategy) { FactoryGirl.strategy_by_name(:create) }

View File

@ -32,7 +32,7 @@ module FactoryGirl
strategy = strategy_class.new
evaluator = evaluator_class.new(strategy, overrides.symbolize_keys)
evaluator = evaluator_class.new(build_class, strategy, overrides.symbolize_keys)
attribute_assigner = AttributeAssigner.new(evaluator, build_class, &instance_builder)
evaluation = Evaluation.new(attribute_assigner, to_create)

View File

@ -145,3 +145,29 @@ describe "initialize_with parent and child factories" do
FactoryGirl.build(:super_awesome).name.should == "Super"
end
end
describe "initialize_with implicit constructor" do
before do
define_class("Awesome") do
attr_reader :name
def initialize(name)
@name = name
end
end
FactoryGirl.define do
factory :awesome do
ignore do
name "Great"
end
initialize_with { new(name) }
end
end
end
it "instantiates the correct object" do
FactoryGirl.build(:awesome, name: "Awesome name").name.should == "Awesome name"
end
end

View File

@ -7,7 +7,7 @@ describe FactoryGirl::EvaluatorClassDefiner do
let(:attributes) { [simple_attribute, relative_attribute, attribute_that_raises_a_second_time] }
let(:class_definer) { FactoryGirl::EvaluatorClassDefiner.new(attributes, FactoryGirl::Evaluator) }
let(:evaluator) { class_definer.evaluator_class.new(stub("build strategy", add_observer: true)) }
let(:evaluator) { class_definer.evaluator_class.new(Object, stub("build strategy", add_observer: true)) }
it "returns an evaluator when accessing the evaluator class" do
evaluator.should be_a(FactoryGirl::Evaluator)