Mr. Tao Mr. Tao - 1 month ago 10
Ruby Question

RSpec with FactoryGirl without Rails – where does it to look for models?

I am writing ActiveRecord Ruby application not using Rails. I would like to test models with FactoryGirl but I am struggling with configuration. Given the uninitialized constant error I guess it can't find models in

lib/models
folder.

I would like to know what folder structure rspec/FactoryGirl expect or how do I inform it about models’ location.

rspec -fd spec/models/user_spec.rb

…/spec/models/user_spec.rb:3:in `<top (required)>': uninitialized constant User (NameError)
from /usr/local/lib/ruby/gems/2.3.0/gems/rspec-core-3.5.4/lib/rspec/core/configuration.rb:1435:in `load'
from /usr/local/lib/ruby/gems/2.3.0/gems/rspec-core-3.5.4/lib/rspec/core/configuration.rb:1435:in `block in load_spec_files'
from /usr/local/lib/ruby/gems/2.3.0/gems/rspec-core-3.5.4/lib/rspec/core/configuration.rb:1433:in `each'
from /usr/local/lib/ruby/gems/2.3.0/gems/rspec-core-3.5.4/lib/rspec/core/configuration.rb:1433:in `load_spec_files'
from /usr/local/lib/ruby/gems/2.3.0/gems/rspec-core-3.5.4/lib/rspec/core/runner.rb:100:in `setup'
from /usr/local/lib/ruby/gems/2.3.0/gems/rspec-core-3.5.4/lib/rspec/core/runner.rb:86:in `run'
from /usr/local/lib/ruby/gems/2.3.0/gems/rspec-core-3.5.4/lib/rspec/core/runner.rb:71:in `run'
from /usr/local/lib/ruby/gems/2.3.0/gems/rspec-core-3.5.4/lib/rspec/core/runner.rb:45:in `invoke'
from /usr/local/lib/ruby/gems/2.3.0/gems/rspec-core-3.5.4/exe/rspec:4:in `<top (required)>'
from ./bin/rspec:17:in `load'
from ./bin/rspec:17:in `<main>'





spec/models/user.rb

describe User, type: :model do
it 'can be instantiated' do
user = User.new
expect(user).to be_a User
end
end


lib/models/user.rb

class User < ActiveRecord::Base
end


I have created RSpec configuration with
rspec --init
:

.rspec

--color
--require spec_helper


spec/spec_helper.rb

require 'factory_girl'
require_relative 'support/factory_girl'

RSpec.configure do |config|
config.expect_with :rspec do |expectations|
expectations.include_chain_clauses_in_custom_matcher_descriptions = true
end

config.mock_with :rspec do |mocks|
mocks.verify_partial_doubles = true
end

config.shared_context_metadata_behavior = :apply_to_host_groups

end


spec/support/factory_girl.rb

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

config.before(:suite) do
FactoryGirl.find_definitions
end
end


spec/factories.rb

FactoryGirl.define do
factory :user do
username "johnny"
end
end

Answer

The part you are missing is that Rails loads all of the models before FactoryGirl from spec_helper.rb when running RSpec test suites.

Try loading all of your models at the top of your spec_helper.rb

root = File.expand_path('../', File.dirname(__FILE__))
Dir[root.join('lib/**/*.rb')].each { |f| require f }

require 'factory_girl'
require_relative 'support/factory_girl'

...