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__)
to:
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
end
Done
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.

Comments
Subscribe Make commentHi, i try to install RSpec (bundle exec rails g rspec:install) but i have an error :
method_missing': undefined methodgenerators’ for #<Rails::Railtie::Configuration:0x00000101b2f1b8> (NoMethodError) from /Users/sentimancho/.rvm/gems/ruby-1.9.2-p0/gems/rspec-rails-2.0.0.beta.18/lib/rspec-rails.rb:4:in `<class:Railtie>’ Any issue ? Thanks in advance.Try upgrading rspec to 2.11.0 sentimancho
I just committed a fix for the “they don’t namespace stuff correctly” issue: https://github.com/rspec/rspec-rails/commit/9ab382c7142fd1885985f1e1b02ea2fad6b05a11
If you have more any more details or reproducible test cases for the other nuances, it’d be great to have them filed as issues in the GitHub repo.
Thanks for the article!
Thanks for the article. Its great and helped a lot.