Emilio Menéndez Emilio Menéndez - 3 months ago 23
Ruby Question

How to configure RSpec to find specs in lib folder?

I am creating a little API with Rails 5.0 following this tutorial http://apionrails.icalialabs.com/book/frontmatter

I am trying to run a test located in

app/config/lib
but RSpec won't find the test.

I have tried adding
config.autoload_paths << Rails.root.join('lib')
or
config.autoload_paths += %W(#{config.root}/lib)
to
app/config/application.rb
.

This is my code:

$ /app/config/application.rb

#required files go here, deleted for clarity.

Bundler.require(*Rails.groups)

module MarketPlaceApi
class Application < Rails::Application

# don't generate RSpec tests for views and helpers
config.generators do |g|
g.test_framework :rspec, fixture: true
g.fixture_replacement :factory_girl, dir: 'spec/factories'
g.view_specs false
g.helper_specs false
g.stylesheets = false
g.javascripts = false
g.helper = false
end

config.autoload_paths += %W(#{config.root}/lib)
end
end


Test

$ app/config/lib/spec/test_spec.rb

require 'spec_helper'

describe ApiConstraints do
#test goes here
end


How can I add the
lib
folder so RSpec runs the tests located in it?

Thanks in advance.

Answer

RSpec doesn't look for tests in autoload_paths. If you run rspec or rake spec without arguments, RSpec looks in the spec directory by default. If you want to run specs in a different directory, give that directory to rspec as an argument:

rspec app/config/lib/spec

However, it's the universal convention to keep your specs in the spec directory, separate from your code in app and lib, so I'd move your specs to spec/lib. RSpec will then find them without any extra effort.

Comments