#spec
let(:price) { create :price,:some_trait,:my_trait }
#factory
FactoryGirl.define do
factory :price, class: 'Prices::Price' do
...
after(:build) do |p,e|
# How I can get the traits passed to the create method?
# => [:some_trait,:my_trait]
if called_traits_does_not_include(:my_trait) # fake code
build :price_cost,:order_from, price:p
end
end
...
end
end
如何在工厂的after(:build)
回调中获得传递给create
的特性?
我不知道有哪个factory_girl特性明确支持这一点。但我可以想到两个部分的解决方案,可能在特定情况下起作用:
-
在trait中设置一个瞬态属性:
trait :my_trait do using_my_trait end factory :price do transient do using_my_trait false end after :build do |_, evaluator| if evaluator.using_my_trait # Do stuff end end end
-
如果你不需要知道在
after :build
回调中使用了什么性状,但你想要跟踪多个性状而不为每个性状添加瞬态属性,请将该性状添加到性状中的after :build
回调列表中:trait :my_trait do after :build do |_, evaluator| evaluator.traits << :my_trait end end factory :price do transient do traits [] end before :create do |_, evaluator| if evaluator.traits.include? :my_trait # Do stuff end end end
(trait中的回调在工厂中相应的回调之前运行,所以如果你在它的回调中注意到一个trait,你最早可以在
before :create
中看到它。)如果你想在许多工厂中跟踪性状,这可能比第一种方法更好,这将使为每个性状添加瞬时属性更加痛苦。