Factory_Girl + RSpec: undefined method 'create' when create(:user)

GigaBass picture GigaBass · Mar 31, 2014 · Viewed 15.4k times · Source

Can't call "dummy = create(:user)" to create a user. Have gone back and forth for hours.

/home/parreirat/backend-clone/Passworks/spec/models/user_spec.rb:15:in `block (2 levels) in <top (required)>': undefined method `create' for #<Class:0xbcdc1d8> (NoMethodError)"

This is the factory, users.rb:

FactoryGirl.define do

    factory :user do
      email '[email protected]'
      password 'chucknorris'
      name 'luis mendes'
    end

end

This is how I call FactoryGirl in the user_spec.rb:

require 'spec_helper'

describe 'User system:' do

 context 'registration/login:' do

    it 'should have no users registered initially.' do
      expect(User.count).to eq(0)
    end

    it 'should not be logged on initially.' do
      expect(@current_user).to eq(nil)
    end

    dummy = create(:user)

    it 'should have a single registered user.' do
      expect(User.count).to eq(1)
    end

  end

end

I added this onto spec_helper.rb as instructed:

RSpec.configure do |config|

   # Include FactoryGirl so we can use 'create' instead of 'FactoryGirl.create'
   config.include FactoryGirl::Syntax::Methods

end

Answer

Bill Turner picture Bill Turner · Apr 1, 2014

You need to move the create line inside of the spec it's being used in:

it 'should have a single registered user.' do
  dummy = create(:user)
  expect(User.count).to eq(1)
end

Right now, that line is without context (not in a spec and not in a before block). That is probably why you're getting the error. You probably have all the setup correct, but just have one line in the wrong place.