mirror of
https://github.com/thoughtbot/factory_bot.git
synced 2022-11-09 11:43:51 -05:00
36cb43e9b0
This allows callbacks (after :build, :create, etc.) to be defined at the FactoryGirl level; this means that the callback will be invoked for all factories. This is primarily to maintain consistency and follow the principle of least surprise. As usual, callbacks are applied from the lowest component to the highest, meaning that global callbacks will be run after factory and trait callbacks are run. FactoryGirl.define do after(:build) {|object| puts "Built #{object}" } factory :user # ... end Closes #481 Closes #486
76 lines
1.8 KiB
Ruby
76 lines
1.8 KiB
Ruby
module FactoryGirl
|
|
module Syntax
|
|
module Default
|
|
include Methods
|
|
|
|
def define(&block)
|
|
DSL.run(block)
|
|
end
|
|
|
|
def modify(&block)
|
|
ModifyDSL.run(block)
|
|
end
|
|
|
|
class DSL
|
|
def factory(name, options = {}, &block)
|
|
factory = Factory.new(name, options)
|
|
proxy = FactoryGirl::DefinitionProxy.new(factory.definition)
|
|
proxy.instance_eval(&block) if block_given?
|
|
|
|
FactoryGirl.register_factory(factory)
|
|
|
|
proxy.child_factories.each do |(child_name, child_options, child_block)|
|
|
parent_factory = child_options.delete(:parent) || name
|
|
factory(child_name, child_options.merge(parent: parent_factory), &child_block)
|
|
end
|
|
end
|
|
|
|
def sequence(name, *args, &block)
|
|
FactoryGirl.register_sequence(Sequence.new(name, *args, &block))
|
|
end
|
|
|
|
def trait(name, &block)
|
|
FactoryGirl.register_trait(Trait.new(name, &block))
|
|
end
|
|
|
|
def to_create(&block)
|
|
FactoryGirl.to_create(&block)
|
|
end
|
|
|
|
def skip_create
|
|
FactoryGirl.skip_create
|
|
end
|
|
|
|
def initialize_with(&block)
|
|
FactoryGirl.initialize_with(&block)
|
|
end
|
|
|
|
def self.run(block)
|
|
new.instance_eval(&block)
|
|
end
|
|
|
|
delegate :before, :after, :callback, to: :configuration
|
|
|
|
private
|
|
|
|
def configuration
|
|
FactoryGirl.configuration
|
|
end
|
|
end
|
|
|
|
class ModifyDSL
|
|
def factory(name, options = {}, &block)
|
|
factory = FactoryGirl.factory_by_name(name)
|
|
proxy = FactoryGirl::DefinitionProxy.new(factory.definition.overridable)
|
|
proxy.instance_eval(&block)
|
|
end
|
|
|
|
def self.run(block)
|
|
new.instance_eval(&block)
|
|
end
|
|
end
|
|
end
|
|
end
|
|
|
|
extend Syntax::Default
|
|
end
|