Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to configure RSpec to load monkey patched classes

I have extended the string class as follows:

class String
  def last_character
    self[-1]
  end
end

I have places the string.rb file in the lib as follows:

lib/core_extensions/string.rb

I have tested the setup and I can use the last_character method in a Rails console.

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

undefined method `last_character' for " ":String

Do I have to tell RSpec to load these class extension files somehow?

like image 207
chell Avatar asked May 25 '17 10:05

chell


2 Answers

One way is to eagerly/explicitly load your custom extensions in the rails_helper.rb

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

Alternative approach

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

like image 134
Sergio Tulentsev Avatar answered Nov 06 '22 21:11

Sergio Tulentsev


Does your spec have require "rails_helper"?

Have you tried restarting Spring?

like image 44
Andy Waite Avatar answered Nov 06 '22 20:11

Andy Waite