Rails 3 + FactoryGirl: NameError: uninitialized constant Factory
Asked Answered
D

4

8
ruby-1.9.2-p180 :007 > Factory.define :user do |user|
ruby-1.9.2-p180 :008 >       user.email                  "[email protected]"
ruby-1.9.2-p180 :009?>     user.password               "foobar"
ruby-1.9.2-p180 :010?>     user.password_confirmation  "foobar"
ruby-1.9.2-p180 :011?>   end
NameError: uninitialized constant Factory

My Gemfile:

group :test do 
  gem "rspec-rails"
  gem 'webrat', '0.7.1'
  gem 'spork', '0.9.0.rc4'
  gem 'factory_girl_rails'
end

Even tough it seems I have everything as it should, I keep getting that error. I also have factories.rb created.

Thanks

Doran answered 8/4, 2011 at 13:7 Comment(0)
P
10

I suppose you try in console in development environment. But you add the Factory gem only in test environment.

If you want access to Factory_girl in development use in your Gemfile :

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

Or if you want test your Factory launch your console in test environment :

rails c test
Papaverine answered 8/4, 2011 at 13:14 Comment(0)
K
2

We had a similar problem on our end, rake spec seemed to be randomly failing with the error uninitialized constant FactoryGirl. The error was random -> coming and going. We went back half a dozen git commits to try and resolve it. In the end it was a silly mistake.

The fundamental problem is RAILS_ENV is set to development. It needs to be set to test when you run rake spec.

Address by:

  1. Making certain that we are running rake spec in the RAILS_ENV test environment and its exported/sourced properly. To never confuse our environemnts, we modified zsh $RPROMPT env variable to show the current env.

    export RPROMPT="[%{$fg_no_bold[yellow]%}$RAILS_ENV%{$reset_color%}]"

  2. Require FactoryGirl in the spec ruby files gave a much better error message. At least rspec would run vs just fail outright this way when the environment was wrong. We also updated our gemfile to make sure factory_girl_rails and factory_girl were loaded both for development and testing.

  3. Now we just run rpsec using the gem guard in a dedicated terminal with the proper RAILS_ENV set.

Its one of those gotchas.

We're running Ruby 1.9.3, Rails 3.2.9, Rspec 2.12, factory_girl 4.1.

Kostman answered 20/12, 2012 at 22:8 Comment(1)
OMG I forgot I had this set!Lubricous
A
2

I also ran into this while I was doing the Hartl tutorial.

If you are using "Spork" to speed up your tests and it is running in the background when you add the FactoryGirl code, you will need to stop it and restart it.

Abdullah answered 11/6, 2013 at 21:23 Comment(0)
B
0

You should also change Factory.define to FactoryGirl.define, like in this example

 FactoryGirl.define do
  factory :user do
    name 'John Doe'
    date_of_birth { 21.years.ago }
  end
end

from the factory_girl documentation

Burkle answered 23/1, 2013 at 15:20 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.