abangratz - blag

Stuff that matters - at least for me.

Minimal Rails App for Gem Development

Surprisingly, the resources for testing gems that have a dependency to rails (or parts thereof) are few and far between. That’s why I decided to have a short howto here for you to peruse, in case you run into the same troubles as we did.

Given the fact that you would need a Rails stack to simulate dependencies, especially if you want to integrate tests, you are stuck with adding a Rails app.

Yes, you are reading correctly: in the end, you need a rails app. But fear not, it’s easier than it sounds.

First, you want to add the dependencies to the Gem spec file:

myproject.gemspec
1
2
3
4
5
6
Gem::Specification.new do |s|
  s.add_development_dependency(%q<rake>)
  s.add_development_dependency(%q<rspec>)
  s.add_development_dependency(%q<rails>)
  s.add_development_dependency(%q<rspec-rails>)
end

If you want to use rspec, rake and all the stuff for running your gems, add the needed Gems to the Gemfile:

Gemfile
1
2
3
4
5
6
group :development do
  gem 'rake'
  gem 'rspec'
  gem 'rails'
  gem 'rspec-rails'
end

Yes, we pull in the whole stack. You can experiment with adding only parts, but that might be hard to accomplish.

Next, you want to create the mini Rails app. The best place is your spec_helper.rb file (in case you are using rspec):

spec_helper.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
require 'action_controller/railtie'
require 'rspec/rails'

require 'myproject'

app = Class.new(Rails::Application)
app.config.secret_token = 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa'
app.config.session_store :cookie_store, :key => '_myproject_session'
app.config.active_support.deprecation = :log
app.config.eager_load = false
app.config.root = File.dirname(__FILE__)
Rails.backtrace_cleaner.remove_silencers!
app.initialize!

This can be also used in test_helper.rb for minitest. And yes, that’s all.

If it doesn’t work for you, get back to me, please, I’m happy to help.

The source is mainly taken from our gem query-interface-server, and has been partially adopted from devise and need_label.

Comments