0

I have subfolders inside the models folder:

app/models/foos/bar.rb

Autoload paths is configured in application.rb:

module AppName
  class Application < Rails::Application
    config.load_defaults 7.0

    config.public_file_server.enabled = true

    config.autoload_paths += Dir[Rails.root.join('app', 'models', '**/')]

This works fine in development, but not in test environment.

development.rb:

config.cache_classes = false
config.eager_load = false

test.rb

config.cache_classes = false
config.eager_load = false

spec/models/bar_spec.rb

describe Bar do
  ....

rspec raises NameError: uninitialized constant Bar

How to autoload the models in test environment?

Rails 7.0.8

2
  • 1
    At the very least shouldn’t the test follow the directory hierarchy of the models? Even if that doesn’t make it work it sure sucks less trying to figure out where things are. Commented Oct 29, 2023 at 19:26
  • What you're doing here makes no sense. With Zeitwerk if you nest bar.rb in a folder below an autoloading root it will autovivify the module and the constant will be loaded as Foos/Bar. Not only are you making the code harder to find but you're also introducing potential bugs and confusion. Just don't man. guides.rubyonrails.org/autoloading_and_reloading_constants.html Commented Oct 29, 2023 at 23:36

1 Answer 1

0

Haha, it was the .rspec file.

Needs to be

--require rails_helper
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.