Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

setting instance variables in factorygirl

Say I have a model like

class Vehicle < ActiveRecore::Base

  after_initialize :set_ivars

  def set_ivars
    @my_ivar = true
  end
end

and somewhere else in my code I do something like @vehicle.instance_variable_set(:@my_ivar, false)

and then use this ivar to determine what validations get run.

How do I pass this Ivar into FactoryGirl?

 FactoryGirl.define do
   factory :vehicle do
      association1
      association2
   end
 end

How do I encode an ivar_set into the above, after create, before save? How do I pass it into a FactoryGirl.create()?

like image 341
Abraham P Avatar asked Feb 14 '14 09:02

Abraham P


1 Answers

FactoryGirl.define do
   factory :vehicle do
      association1
      association2
      ignore do
        my_ivar true
      end

      after(:build) do |model, evaluator|
        model.instance_variable_set(:@my_ivar, evaluator.my_ivar)
      end
    end
 end

 FactoryGirl.create(:vehicle).my_ivar                    #=> true
 FactoryGirl.create(:vehicle, my_ivar: false).my_ivar    #=> false
like image 167
BroiSatse Avatar answered Nov 14 '22 22:11

BroiSatse