Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 549
Gaston Avatar asked Oct 24 '16 00:10

Gaston


1 Answers

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)
like image 122
David Avatar answered Oct 31 '22 15:10

David