How to configure RSpec to load monkey patched classes
Asked Answered
P

2

8

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?

Pawpaw answered 25/5, 2017 at 10:13 Comment(1)
How does your Rails app load this custom extension? Have you created an initializer?Bunce
I
2

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.

Invariable answered 30/5, 2017 at 5:29 Comment(5)
Thank you for that Sergio. Would you know why I have to explicitly do this with Rspec? In other words why doesn't RSpec just load them automatically?Pawpaw
@chell: I'm guessing because you either a) don't load rails environment in rspec or b) don't have that folder in autoload_paths/eager_load_paths.Invariable
Hi Sergio, I think I do load rails environment in rspec as I have the following in my rails_helper file: require File.expand_path('../../config/environment', FILE). I think your point b) may be the issue: I have this in my application.rb: config.eager_load_paths << "#{Rails.root}/lib However, inside of environment/tests.rb I have: config.eager_load = falsePawpaw
I just tested changing config.eager_load to true and removing the code you gave me and it all works. So really the answer should be that I needed to set config.eager_load=true to load my custom extensions.Pawpaw
@chell: eager loading in test is an alternative approach. The one in my answer is also very popular.Invariable
D
1

Does your spec have require "rails_helper"?

Have you tried restarting Spring?

Dawnedawson answered 28/5, 2017 at 12:42 Comment(3)
Yes I have require 'rails_helper' and I have restarted Spring.Pawpaw
If you're able to share your repo on GitHub I can take a look.Dawnedawson
Unfortunately I'm unable to share my repository.Pawpaw

© 2022 - 2024 — McMap. All rights reserved.