[英]FactoryGirl - Retrieving the build strategy from an evaluator
根据FactoryGirl文档:
after(:build)-建立工厂后调用(通过FactoryGirl.build,FactoryGirl.create)
在我的代码中,我希望回调逻辑根据构建策略而有所不同(在FactoryGirl中称为strategy_name
)。
一些伪代码:
after(:build) do |o, evaluator|
if evaluator.???.strategy_name == 'create'
# logic
elsif evaluator.???.strategy_name == 'build'
# other logic
end
end
有谁知道我如何利用回调中的evaluator
获取strategy_name
?
在深入探讨FactoryGirl的源代码之后,我无法找到支持的方法。 我最终打开了Evaluator类,并添加了一些谓词方法。 将以下内容添加到您的spec_helper
, test_helper
或支持文件中。
module FactoryGirl
class Evaluator
def strategy_create?
@build_strategy.class == Strategy::Create
end
def strategy_build?
@build_strategy.class == Strategy::Build
end
def strategy_attributes_for?
@build_strategy.class == Strategy::AttributesFor
end
def strategy_stub?
@build_strategy.class == Strategy::Stub
end
def strategy_null?
@build_strategy.class == Strategy::Null
end
end
end
在您的工厂中:
after(:build) do |o, evaluator|
if evaluator.strategy_create?
# logic
elsif evaluator.strategy_build?
# other logic
end
end
我正在使用FactoryGirl 4.4.0。 看起来这在> = 3.0.0时可以使用,但是您的里程可能会有所不同。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.