Search code examples
ruby-on-railsfactory-bothas-manybelongs-to

FactoyGirl: before(:create) actions not being recognized


I am attempting to create my FactoryGirl factories such that when I call FactoryGirl.create(:model_a), any dependency for model_a are created and assigned to that model_a factory. However, for some reason my method is not working and I can't quite figure out why.

In my factory file this is what I have:

FactoryGirl.define do
    factory :model_a do
        before(:create) do
            FactoryGirl.create(:model_b)
        end

        model_b {ModelB.first}
    end
end

Now when I run FactoryGirl.create(:model_a) I would expect this to first create the factory model_b (because of the before(:create) call) and then go back to creating the factory model_a and assigning the factory model_b to the model_b relationshionship for model_a

But instead, I am getting the error model_b must exist, model_b cannot be blank.

Why is the factory model_b not being created so that I can use it?


Solution

  • You need to set the association between model_a and model_b inside your before(:create) block. For example:

    FactoryGirl.define do
      factory :model_a do
        # add model_a attributes as needed
    
        before(:create) do |model_a|
          model_a.model_b = ModelB.first || FactoryGirl.create(:model_b)
        end
      end
    end
    

    Or, per OP's comment:

    factory :model_a do
      # add model_a attributes as needed
      model_b { ModelB.first || FactoryGirl.create(:model_b) }
    end