'Factory Girl pass parameter to trait
I've been banging my head over this. I want to be able to overwrite attributes on top of traits. I've been reading the documentation and some internet examples but I can't get it to work.
This is sort of what I want to do:
test "..." do
#overwrite start_time
middle = create( :basic_instant_instance, start: 1.hours.ago)
end
FactoryGirl.define do
factory :instant_instance do
trait :active_now do
#attributes...
transient do
start nil
end
#overwrite start_time
start_time start.present? ? start : Time.now
end
factory :basic_instant_instance, traits: [:active_now]
end
I keep getting:
ArgumentError: Trait not registered: start
Solution 1:[1]
You need to rethink your strategy a little here - you have a basic_instant_instance
which does not inherit from instant_instance
and therefore knows nothing about the trait [:active_now] or start attribute.
You also need to be evaluating the start_time at the time you are building the Factory instance by placing it in curly brackets. Otherwise it will be evaluated before start is initialised.
Try something like the following:
FactoryGirl.define do
factory :instant_instance do
trait :active_now do
# attributes...
transient do
start { nil }
end
# overwrite start_time
start_time { start.present? ? start : Time.now }
end
end
end
and then call it like so:
create(:instant_instance, :active_now, start: 1.hours.ago)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Paweł Gościcki |