Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
like image 264
parreirat Avatar asked Mar 30 '14 23:03

parreirat


3 Answers

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.

like image 152
Bill Turner Avatar answered Nov 20 '22 19:11

Bill Turner


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.

like image 23
Jason Swett Avatar answered Nov 20 '22 19:11

Jason Swett


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

like image 1
Kaka Ruto Avatar answered Nov 20 '22 19:11

Kaka Ruto