parreirat
parreirat

Reputation: 715

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

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

Upvotes: 17

Views: 16239

Answers (3)

Kaka Ruto
Kaka Ruto

Reputation: 5125

Sometimes you just need to require 'rails_helper' at the top of your test file. This solved mine.

Upvotes: 1

Jason Swett
Jason Swett

Reputation: 45074

Another reason for getting the undefined method 'create' error could be that you're missing this piece of configuration in spec/support/factory_girl.rb:

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

I found that code here.

Upvotes: 9

Bill Turner
Bill Turner

Reputation: 3697

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.

Upvotes: 9

Related Questions