Testing controllers in Rails 4 engines

Testing controllers in Rails engines with RSpec requires you to jump through some hoops. If memory serves, it was slightly trickier in Rails 3 than it is now in Rails 4. Fortunately the fix is pretty easy, if not obvious.

By the way, I’m standing on the shoulders of giants here. What I’ve done is to combine the most useful parts of two particular Stack Overflow answers, remove the now incorrect/irrelevant parts, and spoon-feed you the solution in the form of a complete example.

First we’ll create our engine which we’ll call “Appointly.” (It’s an imaginary appointment scheduling gem.)

Next step is to add the rspec-rails gem to our gemspec:

And install RSpec:

Everything has been straightforward so far. Now is where we have to modify spec/spec_helper.rb in exactly two places. I’ve tried to make it blatantly obvious what exactly it is you need to change.

In addition to changing those paths, we have to tell our engine to use RSpec as the default test framework:

And now we’re good to go. Let’s generate a scaffold and create/migrate our database.

If we run one of our controller specs now…

…it will fail. What happened? My understanding here is that since our engine is an *isolated* engine – an engine designed not to interfere with the routes, helpers, etc. defined in your application – we need to *explicitly* say we’re using Appointly routes, not the dummy app’s routes. Add use_route: :appointly to your spec:

Run the spec again…

…and it will pass.

The following two tabs change content below.

Starr Horne

Co-founder at Honeybdager.io
Starr Horne is a Rubyist and Chief Javascripter at Honeybadger.io. When he's not neck-deep in other people's bugs, he enjoys making furniture with traditional hand-tools, reading history and brewing beer in his garage in Seattle.