rspec / rspec-core

RSpec runner and formatters
http://rspec.info
MIT License
1.23k stars 765 forks source link

being able to set custom rspec load path #2963

Closed tansaku closed 2 years ago

tansaku commented 2 years ago

Subject of the issue

I'm looking at a legacy app that has a lot of ruby code in an api folder on the root, and a fair amount of custom code to load it to be accessible by the specs. I'm wondering if there's a simple config option to allow it to be auto-loaded as if the code was in the app or lib directories?

I've been reading through the docs but not immediately seeing a way to do this https://relishapp.com/rspec/rspec-core/v/3-11/docs/configuration

Your environment

Steps to reproduce

create an rspec ruby setup, but place the ruby code under test in a folder called api

Expected behavior

by specifying code is in an api folder by some config specs within spec/api would find code in the root api folder

Actual behavior

custom loading required to auto load code under test in api folder

I realise the response may be, just put your code in lib/api but I'm just wondering if there's a hidden config option to make allow us to refactor our legacy app without changing directory structure in the first instance

Many thanks in advance 🙏

tansaku commented 2 years ago

Ah, could I do it with?

RSpec.configure do |c|
  c.default_path = 'api'
end

That doesn't immediately seem to work, but I guess once api is the default path then api would have to be removed from the spec path ...

JonRowe commented 2 years ago

RSpec doesn't do any autoloading, thats down to other libraries (as in Rails, where its Zeitwerk et al) or in built Ruby semantics (such as the autoload directive). You can tweak which folders are available in this fashion by tweaking the ruby options to have ./api on your load path (even programatically via $LOAD_PATH, which is what gems do in their gemspecs) but this is out of scope for an RSpec feature.

tansaku commented 2 years ago

thanks @JonRowe so then this RSpec config that adds lib/ to directories is not controlling which directories are checked for ruby code when RSpec is running? https://github.com/rspec/rspec-core/issues/1983 ... ah sorry okay, so I think I'm mixing up autoload with which dirs are on the LOAD_PATH ... if I use:

  config.default_path = 'api'

then I can require files without needing relative paths ...

JonRowe commented 2 years ago

The config option is to allow you do e.g. --require 'spec_helper' and have it mean spec/spec_helper.rb, like gemspecs we also add lib at that point as discussed, but there is no autoloading done, just a manipulation of the load path which you can do yourself without our help