Testing controllers in Rails 4 engines

How to test controllers in Rails 4 engines. Testing controllers in Rails engines with Rspec requires jumping through some hoops but it's actually pretty easy.

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.)

$ rails plugin new appointly --mountable -T --dummy-path=spec/dummy

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

# appointly.gemspec

s.add_dependency "rspec-rails", "~> 2.14.1"

And install RSpec:

$ bundle install
$ rails generate rspec:install

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.

# spec/spec_helper.rb

# This file is copied to spec/ when you run 'rails generate rspec:install'
ENV["RAILS_ENV"] ||= 'test'

################################################################
# Change this
# require File.expand_path("../../config/environment", __FILE__)
#
# to this
require File.expand_path("../dummy/config/environment", __FILE__)
################################################################

require 'rspec/rails'
require 'rspec/autorun'

# Requires supporting ruby files with custom matchers and macros, etc,
# in spec/support/ and its subdirectories.

################################################################
# Change this
# Dir[Rails.root.join("spec/support/**/*.rb")].each { |f| require f }
# To this
ENGINE_RAILS_ROOT=File.join(File.dirname(__FILE__), '../')
Dir[File.join(ENGINE_RAILS_ROOT, "spec/support/**/*.rb")].each {|f| require f }
################################################################

# Checks for pending migrations before tests are run.
# If you are not using ActiveRecord, you can remove this line.
ActiveRecord::Migration.check_pending! if defined?(ActiveRecord::Migration)

RSpec.configure do |config|
# ## Mock Framework
#
# If you prefer to use mocha, flexmock or RR, uncomment the 
# appropriate line:
#
# config.mock_with :mocha
# config.mock_with :flexmock
# config.mock_with :rr

# Remove this line if you're not using ActiveRecord or ActiveRecord
# fixtures
config.fixture_path = "#{::Rails.root}/spec/fixtures"

# If you're not using ActiveRecord, or you'd prefer not to run each of 
# your examples within a transaction, remove the following line or
# assign false instead of true.
config.use_transactional_fixtures = true

# If true, the base class of anonymous controllers will be inferred
# automatically. This will be the default behavior in future versions of
# rspec-rails.
config.infer_base_class_for_anonymous_controllers = false

# Run specs in random order to surface order dependencies. If you find
# an order dependency and want to debug it, you can fix the order by 
# providing the seed, which is printed after each run.
# --seed 1234
config.order = "random"
end

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

# lib/appointly/engine.rb

module Appointly
class Engine < ::Rails::Engine
isolate_namespace Appointly

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

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

$ rails g scaffold appointment start_time:datetime
$ rm -rf test # For some reason Rails still generates the test directory
$ rake db:create
$ rake db:migrate RAILS_ENV=test

If we run one of our controller specs now...

$ rspec spec/controllers/appointly/appointments_controller_spec.rb:34

...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:

describe "GET index" do
it "assigns all appointments as @appointments" do
appointment = Appointment.create! valid_attributes
# get :index, {}, valid_session
get :index, { use_route: :appointly }, valid_session
assigns(:appointments).should eq([appointment])
end
end

Run the spec again...

$ rspec spec/controllers/appointly/appointments_controller_spec.rb:34

...and it will pass.

What to do next:
  1. Try Honeybadger for FREE
    Honeybadger helps you find and fix errors before your users can even report them. Get set up in minutes and check monitoring off your to-do list.
    Start free trial
    Easy 5-minute setup — No credit card required
  2. Get the Honeybadger newsletter
    Each month we share news, best practices, and stories from the DevOps & monitoring community—exclusively for developers like you.
    author photo

    Starr Horne

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

    More articles by Starr Horne
    Stop wasting time manually checking logs for errors!

    Try the only application health monitoring tool that allows you to track application errors, uptime, and cron jobs in one simple platform.

    • Know when critical errors occur, and which customers are affected.
    • Respond instantly when your systems go down.
    • Improve the health of your systems over time.
    • Fix problems before your customers can report them!

    As developers ourselves, we hated wasting time tracking down errors—so we built the system we always wanted.

    Honeybadger tracks everything you need and nothing you don't, creating one simple solution to keep your application running and error free so you can do what you do best—release new code. Try it free and see for yourself.

    Start free trial
    Simple 5-minute setup — No credit card required

    Learn more

    "We've looked at a lot of error management systems. Honeybadger is head and shoulders above the rest and somehow gets better with every new release."
    — Michael Smith, Cofounder & CTO of YvesBlue

    Honeybadger is trusted by top companies like:

    “Everyone is in love with Honeybadger ... the UI is spot on.”
    Molly Struve, Sr. Site Reliability Engineer, Netflix
    Start free trial