Zhu Wu's Blog

The world is a fine place and worth fighting for.

Require Files From Gem's Spec Folder

As a ruby programmer, you probably already know that the code files in gem's lib folder are automatically loaded into $LOAD_PATH when you require the gem.

Today, I encountered a scenario that I have to manually load source code files from spec folder. The rails app is using a gem which defines some models, and I have a controller to manipulate models defined by the gem. When writing unit tests for the controller and setting up some objects of the models for testing using factory_girl, I notice that the source code files which define factories for the models are not inside the gem's lib folder. Instead, they are located in spec/factories folder. Thus, those factory files are not automatically loaded.

It turns out that I have to find a way to manually require those factory files. The solution is quite simple:

GEM_ROOT = Gem.loaded_specs['gem_name'].full_gem_path
Dir[File.join(GEM_ROOT, 'spec', 'factories', '*.rb')].each { |file| require(file) }

The first line of code above gets the actual path to the specific gem, and the second line just construct the path and require every ruby file under that path. In this way, the factory files are loaded, and I can use them to create testing objects and continue to write unit tests.