Search code examples
ruby-on-railsfunctional-testing

Testing a ApplicationController before_filter in Rails


I have an application that detects the subdomain on a request and sets the result to a variable.

e.g.

before_filter :get_trust_from_subdomain

def get_trust_from_subdomain
  @selected_trust = "test"
end

How can I test this with Test::Unit / Shoulda? I don't see a way of getting into ApplicationController and seeing what's set...


Solution

  • The assigns method should allow you to query the value of @selected_trust. To assert that its value equals "test" as follows:

    assert_equal 'test', assigns('selected_trust')
    

    Given a controller foo_controller.rb

    class FooController < ApplicationController
      before_filter :get_trust_from_subdomain
    
      def get_trust_from_subdomain
        @selected_trust = "test"
      end
    
      def index
        render :text => 'Hello world'
      end
    end
    

    one might write a functional test as follows in foo_controller_test.rb:

    class FooControllerTest < ActionController::TestCase
      def test_index
        get :index
        assert @response.body.include?('Hello world')
        assert_equal 'test', assigns('selected_trust')
      end
    end
    

    Related to comment: note that the filter can be placed in ApplicationController and then any derived controller will also inherit this filter behaviour:

    class ApplicationController < ActionController::Base
      before_filter :get_trust_from_subdomain
    
      def get_trust_from_subdomain
        @selected_trust = "test"
      end
    end
    
    class FooController < ApplicationController
      # get_trust_from_subdomain filter will run before this action.
      def index
        render :text => 'Hello world'
      end
    end