Skip to content

Instantly share code, notes, and snippets.

@jwietelmann
Created January 12, 2016 17:37
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jwietelmann/da26416344c6538c6761 to your computer and use it in GitHub Desktop.
Save jwietelmann/da26416344c6538c6761 to your computer and use it in GitHub Desktop.
An RSpec sanity check to run against every Rails controller.
# What the heck is this spec about?
#
# It's a gut-check that runs against every controller in the application.
# It is NOT a replacement for writing controller specs for each controller.
#
# What this does is things like check to make sure you didn't forget to lock
# down the index action of a controller to authorized users, checks to see if
# common routes are throwing silly errors, etc.
#
# Your controller passing these tests does not guarantee that it is healthy.
# But if it fails these, there's a 99.9% chance that it's unhealthy.
#
# That is the kind of test that should live here:
# The kind that,
# for nearly every controller,
# will indicate a serious problem 99.9% of the time.
#
# Use wisely.
require 'rails_helper'
# TODO: Load every controller. Not every class in the application.
Rails.application.eager_load!
# A Set of Controller classes for which the index action is not behind a login
# wall
public_index_whitelist = Set.new []
ApplicationController.descendants.each do |controller|
RSpec.describe controller, type: :controller do
include Warden::Test::Helpers
include Devise::TestHelpers
Warden.test_mode!
# Index actions are a great target for these not-very-controller-dependent
# tests because they almost always have the same behavioral expectations
# in the simplest case
if controller.method_defined? :index
it 'should not throw an error for GET `index` without params, even when the user is not authenticated' do
get :index, format: :json
end
# Except for specific controllers, expect the index action to require
# authorization
unless public_index_whitelist.include? controller
it 'should require authorization for GET `index`' do
get :index, format: :json
expect(response.response_code).to eq(401)
end
end
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment