mike927
mike927

Reputation: 774

Rails FactoryGirl instance variable

I would like to create factory using local variable. Currently I have the following factory:

FactoryGirl.define do
  factory :offer_item, class: BackOffice::OfferItem do
    service
    variant
  end
end

My expectation is to create something like below

 FactoryGirl.define do
    variant = FactroyGirl.create(:variant)
    factory :offer_item, class: BackOffice::OfferItem do
      service
      variant { variant }

      after(:create) do |offer_item|
        offer_item.service.variants << variant
      end
    end
  end

but then I get:

/.rvm/gems/ruby-2.2.3/gems/factory_girl-4.7.0/lib/factory_girl/registry.rb:24:in `find': Factory not registered: variant (ArgumentError)

All models are nested inside BackOffice module. Generally I want the same object has association with two other objects. I think there is a some problem with scope in my factory.

Variant factory is inside other separated file.

Upvotes: 0

Views: 972

Answers (1)

Keith
Keith

Reputation: 1504

The issue is you are trying to create a factory before FactoryGirl has finished loading all of the factory definitions. This is because you defined the variable at the scope of a factory definition. Even if this did work, you would likely end up sharing the same variant record between multiple offer_items that you create in your test because this code would only get executed once during initialization.

Since you defined an association to Variant, you probably don't need to create it as an extra step. We can leverage FactoryGirl's ability to create our associations for us and then copy the object into your #service in your after(:create) callback. Maybe it would look something like this (untested):

FactoryGirl.define do

  factory :offer_item, class: BackOffice::OfferItem do
    service
    variant

    after(:create) do |offer_item|
      offer_item.service.variants << offer_item.variant
    end
  end
end

Upvotes: 2

Related Questions