NameError: uninitialized constant Factory
Asked Answered
U

3

17

I'm following this tutorial to get started with TDD on rails with factory girl, rspec and i ran into this issue i can't get my head around.

Here's my "factory".rb (events.rb)

require 'faker'

FactoryGirl.define do
   factory :event do
     name "HIGH"
     genre "house, techno, idb"
     venue_name "Westbourne Studios"
     venue_address "4-6 Chamberlayne Road"
     venue_postcode "NW103JD"
     begin_time "10pm"
     end_time "2am"
     user_id 2
     description "A Super massive party with loads of everything you would want around."
     status true
     venue_id nil
   end
end

and here's the event_spec.rb:

require 'spec_helper'
require 'factory_girl_rails'

describe Event do

it "has a valid factory" do
  Factory.create(:event).should be_valid
end

  it "is invalid without a name"
  it "is invalid without a genre"
  it "is invalid without a venue_name"
  it "is invalid without a venue_address"
  it "is invalid without a venue_postcode"
  ...

 end

I have setup the model, migrated etc.. and when i run "rspec spec/models/event_spec.rb" i get the following error:

Failures:

1) Event has a valid factory
 Failure/Error: Factory.create(:event).should be_valid
 NameError:
   uninitialized constant Factory
 # ./spec/models/event_spec.rb:7:in `block (2 levels) in <top (required)>'

 Finished in 0.1682 seconds
 13 examples, 1 failure, 12 pending

 Failed examples:

 rspec ./spec/models/event_spec.rb:6 # Event has a valid factory

 Randomized with seed 64582
Unguinous answered 11/9, 2012 at 21:59 Comment(0)
V
57

Try to use it in this way:

FactoryGirl.create(:event).should be_valid

I think, I can remember, that it was only "Factory" in old versions of the gem. If you take a look in the recent "Getting started" guide of Factory Girl, there are only calls with "FactoryGirl".

Viscid answered 11/9, 2012 at 22:7 Comment(2)
i knew it was going to be something stupid... thanks a lot :)Unguinous
Factory was deprecated in previous versions, I assume that it is removed in the current versionKaraite
I
10

If you create file spec/support/factory_girl.rb with content:

RSpec.configure do |config|
  config.include FactoryGirl::Syntax::Methods
end

Then you can simply use:

create(:event)
build(:book)

Instead of:

FactogyGirl.create(:event)
FactogyGirl.build(:book)
Isabellaisabelle answered 23/11, 2012 at 14:58 Comment(0)
E
2

I had the same error with factory bot, and to supplement Stefan's answer I came across this little cheat sheet.

https://devhints.io/factory_bot

Empressement answered 8/11, 2017 at 6:22 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.