Sharing test resources from a Ruby gem

We recently split out all of our Rails model classes into a separate gem: that way multiple apps/engines can all share the models. As a result, all of the Fabricators (using Fabrication gem), our test fixtures, also got moved into the new gem. Since the original Rails app’s specs are using those fabricators, our specs no longer succeeded.

Unfortunately, Rubygems and Bundler do not have the concept of a test artifact that exists in Maven, for example. Therefore, it is not clear how one might share testing resources.

To resolve this, I added the fabricators to the test_files of the gem. In my case, it looks like this in my gemspec:

...
Gem::Specification.new do |s|
  ...
  s.test_files = Dir['spec/fabricators/**/*']
  ...
end

If your gem is a Rails engine, be sure not to include the dummy app’s log folder in the test_files of the gem!

Next, to make the fabricators available to code that uses that gem as a dependency, I added a file called “spec/support/fabrication.rb” (which gets loaded by spec_helper.rb) that looks like:

Fabrication.configure do |config|
  nameofgem_gem_spec = Bundler.rubygems.find_name('nameofgem').first
  config.path_prefix = nameofgem_gem_spec.full_gem_path
end

Voila, Fabrication gem can load the Fabricators from my external models gem! Obviously, this is a one-off solution. It’s definitely not a general means of having test resources. However, it worked for me. Let me know if you have success with this approach, or if you have ideas about how to do it better.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.