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

3

17

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
Presnell answered 30/3, 2014 at 23:42 Comment(0)
B
9

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.

Broadcasting answered 31/3, 2014 at 23:30 Comment(2)
Wow, that worked. But why? What's the reason? What difference does it make exactly, being inside and outside of it's? Thanks!Presnell
@GigaBass: I didn't look too closely at the FactoryGirl source code, but my guess is that those methods (create, attributes_for, etc) are only exposed within a test or spec. Where you placed it in your test file is sort of nowhere, so those methods aren't available. Make sense? And if the answer is right, please accept it.Broadcasting
P
9

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.

Pentane answered 15/6, 2017 at 1:5 Comment(1)
Also, don't forget to require it from rails_helper.rb like this: require 'support/factory_bot'. FYI: FactoryGril is now called FactoryBot.Conspecific
C
1

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

Cascabel answered 18/7, 2018 at 0:52 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.