Created
May 25, 2015 01:47
-
-
Save jamesmartin/fc3f361778bd9f9e12ab to your computer and use it in GitHub Desktop.
Testing ApplicationController before_filter methods using RSpec's "anonymous" controller instance
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class ApplicationController < ActionControllerBase | |
helper :do_something | |
def do_something | |
@from_do_something = params[:for_do_something] | |
end | |
end |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require 'rails_helper' | |
describe ApplicationController do | |
controller do | |
before_filter :do_something | |
def action_requiring_filter | |
render nothing: true | |
end | |
end | |
before(:each) do | |
routes.draw do | |
get 'action_requiring_filter' => 'anonymous#action_requiring_filter' | |
end | |
end | |
context "when an action requires a before filter" do | |
it "runs the filter" do | |
get :action_requiring_filter, for_do_something: 'some value' | |
expect(assigns[:from_do_something]).to eq('some value') | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This is not to suggest that it's a good idea to have before filters that set instance variables, but if you do need to test them, this technique at least makes the controller behave more like the real world. Too often I see tests that directly call the filter method on the
ApplicationController
, which can work in certain circumstances, but normally requires a bunch of stubbing of params and environment details because the method is being called outside of the normal Rails request/response cycle.This also demonstrates a way to test any actions that depend on "inherited" behavior from
ApplicationController
, using RSpec's anonymous controller context and some test routes.