Testing Rails Engines With Rspec

After my lightning talk at Ruby North East, a couple of people asked me how to go about getting set up with an engine with RSpec as the testing framework. We’ve automated this at Sage, but here’s what’s necessary.

Generate a new engine

rails plugin new myengine --mountable --dummy-path=spec/dummy -T --skip-bundle
  • plugin new — Tells Rails we’re generating a plugin
  • —mountable — Tells Rails that it’s a mountable engine
  • —dummy-path=spec/dummy — Makes the dummy application generate in the ‘spec’ folder as opposed to ‘test’
  • -T — Disables test_unit
  • —skip-bundle — Not strictly necessary but saves a few minutes/hours of your life

Add RSpec to the Gemfile

Add to your Gemfile:

gem 'rspec-rails'

And then run:

bundle install

Install RSpec

bundle exec rails g rspec:install

Modify spec_helper to know about the dummy app

The default generated spec_helper will try to load your Rails environment from the wrong place. So, change:

require File.expand_path("../../config/environment", __FILE__)


require File.expand_path("../../spec/dummy/config/environment", __FILE__)

Now the dummy app’s environment will be loaded instead.

Use RSpec Generators

Now this step isn’t strictly necessary, as RSpec’s default Rails test generators simply don’t work with engines (they don’t namespace stuff correctly and they don’t know how to handle engine route helpers).

Nevertheless, you may want to enable them purely for the creation of the correct files, which you can modify after generation to work correctly.

If so, add the following to your “lib/myengine/engine.rb” file, inside the Engine class:

config.generators do |g|                                                               
  g.test_framework :rspec
  g.integration_tool :rspec


You should now have a working rspec, and when you run ‘bundle exec rspec spec’, it will load your dummy app’s environment for testing.


Make comment
No comments for this post