How to configure RSpec to load shared monkey classes

I extended the string class as follows:

class String def last_character self[-1] end end 

I have a string.rb file in lib as follows:

 lib/core_extensions/string.rb 

I tested the installation and I can use the last_character method in the Rails console.

However, when I run the RSpec test for a class that uses the extended String class, it gives me an error:

 undefined method `last_character' for " ":String 

Should I tell RSpec to load these class extensions somehow?

+8
ruby-on-rails-5 rspec
source share
2 answers

One way is to look / explicitly load custom extensions into rails_helper.rb

 Dir[Rails.root.join('lib/core_extensions/*.rb')].each { |f| require f } 

Alternative approach

Add this folder to eager_load_paths and set config.eager_load = true in config/environments/test.rb

+2
source share

Does your specification require "rails_helper" ?

Have you tried restarting Spring?

+1
source share

All Articles