Config.autoload_paths help needed for Rails 4

From week 3: Interacting with 3rd party services

When setting up the fake for the twitter response, we create fake_twitter_spec.rb and fake_twitter.rb in spec/lib. Initially, fake_twitter_spec.rb fails because fake_twitter.rb isn’t getting autoloaded:

uninitialized constant FakeTwitter (NameError)

In the video, this gets fixed when Josh adds the following to config/application.rb:

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

I’m confused as to why this woks. Doesn’t this line just autoload the files in config/lib. Why does it also work for spec/lib?

I’m working in Rails 4 and

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

doesn’t work for me. I also tried

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

but I get an error:

`method_missing': undefined method `spec' for #<Hashtag::Application:0x007f9c8c86e680> (NoMethodError)

Any suggestions on how I can get this working for Rails 4?

I got this to work by adding the following to spec_helper.rb:

require_relative "../spec/lib/fake_twitter.rb"

I’d appreciate some feedback on whether or not this is the proper way to get it working per rails conventions.

That looks fine to me.


@Chris_Bradley I just tried the config.autoload_paths line in Rails 4 and had no issues. Can you make the app public on GitHub so I can poke around? You shouldn’t have to use require_relative anywhere in your app, so I’m hesitant to suggest that solution since it’s almost always an indicator that something else isn’t configured correctly.

Here’s the repo:

Right now it’s is in the broken state: in config/application:21

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

and spec/spec_helper.rb:6

# require_relative "../spec/lib/fake_twitter.rb"

Thanks for taking a look.

@Chris_Bradley I didn’t realize this before but you put FakeTwitter within spec/lib, which is incorrect; instead, that file should live within lib/ in the Rails root directory.

Hope this helps!

1 Like

immensely, thank you.