Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails 3 + FactoryGirl: NameError: uninitialized constant Factory

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

like image 934
donald Avatar asked Apr 08 '11 13:04

donald


3 Answers

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
like image 113
shingara Avatar answered Nov 05 '22 15:11

shingara


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.

like image 22
Geoffrey Shmigelsky Avatar answered Nov 05 '22 15:11

Geoffrey Shmigelsky


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.

like image 2
Gregism Avatar answered Nov 05 '22 13:11

Gregism