Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

FactoryGirl creating objects in development environment

When I boot up my rails console in development I see FactoryGirl creating objects. Clearly I'm doing it wrong, but what's the right way to do this? This code makes my tests work...

# tests/factories/board.rb
FactoryGirl.define do

    factory :word do
        sequence(:text) { |n| "FAKETEXT#{n}" }
    end

    factory :board do
        trait :has_words do
            words [
                FactoryGirl.create(:word, id: "514b81cae14cfa78f335e250"),
                FactoryGirl.create(:word, id: "514b81cae14cfa7917e443f0"),
                FactoryGirl.create(:word, id: "514b81cae14cfa79182407a2"),
                FactoryGirl.create(:word, id: "514b81cae14cfa78f581c534")
            ]
        end
    end

end

Note there's no mention of factory anything in any file in my config directory, so whatever loading is happening automatically by the gem. The relevant part of my Gemfile reads:

# Stuff not to use in production
group :development, :test do
    # Command-line debugger for development
    gem "debugger"

    # for unit testing - replace fixtures
    gem "factory_girl_rails"
end

So I could just take factory girl out of the development environment. But I think the fact that these records are being created before the factory is being used is a sign that I've written my factory incorrectly. But if you tell me the factory is written correctly, I'll just do that.

like image 736
Leopd Avatar asked Apr 18 '13 20:04

Leopd


Video Answer


1 Answers

Had the same problem. There are 2 ways to fix this,

1. Use FactoryGirl syntax to reference Factory within a Factory.

Replace FacotryGirl.create(:my_factory) with factory: :my_factory

More info on this, https://github.com/thoughtbot/factory_girl/blob/master/GETTING_STARTED.md#associations

2. factory_girl :require => false in Gemfile

This causes Factories to generate objects on boot,

group :development, :test do  
  gem 'factory_girl_rails'
end  

Why? During Rails boot, Bundler requires all the gems in the development group, and it seems that FactoryGirl requires all their factory files. Requiring the factories evaluates the Ruby code, and thus, FactoryGirl.create(:my_factory) gets called.

This can be fixed by,

# Gemfile
group :development, :test do  
  gem 'factory_girl_rails', :require => false
end  

Just make sure to manually require factory_girl in your test environment, EG

# spec_helper
require 'factory_girl'
like image 200
westonplatter Avatar answered Sep 20 '22 03:09

westonplatter