FactoryGirl.define do
factory :user do
name ''
email ''
after(:build) do |user, evaluator|
# is there any way to get the following returned result?
puts some_code_that_will_return_the_arguments_passed
# => {name: 'Foo', email: 'foobar@example.com'}
end
end
end
FactoryGirl.build(:user, name: 'Foo', email: 'foobar@example.com')
FactoryGirl.define do
factory :user do
transient do
build_from []
end
name ''
email ''
after(:build) do |user, evaluator|
puts evaluator.build_from.map{|attribute| [attribute, user[attribute]] }.to_h
# => {name: 'Foo', email: 'foobar@example.com'}
end
end
end
FactoryGirl.build(:user, name: 'Foo', email: 'foobar@example.com', build_from: [:name, :email])
build_from
。不幸的是,我无法通过官方文档或互联网上的任何内容找到任何内容。
答案 0 :(得分:0)
在检查 factory_girl 源代码之后,在查看文档之后,我找不到任何公共API来访问参数,因此我编写了自己的" safe"猴子补丁。
重要:强>
def initialize
完全相同(仅限猴子修补修改)使用以下内容创建一个新文件: config / initializers / factory_girl_patch.rb :
require 'factory_girl/evaluator'
module FactoryGirl
class Evaluator
attr_reader :overrides_arguments # MONKEY-PATCH: ADDED LINE
def initialize(build_strategy, overrides = {})
# MONKEY-PATCH-START: ADDED LINES
monkey_patch_tested_version = '4.7.0'
if Gem.loaded_specs['factory_girl'].version.version != monkey_patch_tested_version
raise "This monkey-patched code is only tested on #{monkey_patch_tested_version}. Verify source code differences with your version first by inspecting lib/factory_girl/evaluator.rb file."
end
@overrides_arguments = overrides.clone # WHAT WE NEED
# MONKEY-PATCH-END
@build_strategy = build_strategy
@overrides = overrides
@cached_attributes = overrides
@instance = nil
@overrides.each do |name, value|
singleton_class.define_attribute(name) { value }
end
end
end
end
FactoryGirl.define do
factory :user do
name ''
email ''
after(:build) do |user, evaluator|
puts evaluator.overrides_arguments
# => {name: 'Foo', email: 'foobar@example.com'}
end
end
end
FactoryGirl.build(:user, name: 'Foo', email: 'foobar@example.com')