Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • before_filter TestCase for ApplicationController using "Unit Test" approach or "test-unit" gem

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 360
    Comment on it

    I am using Browsernizer gem to prevent some browsers version from accessing website and redirect to a static instruction page to upgrade browser version.

    So using before_filter method in ApplicationController to detect browser version & redirect to a page. The problem is, without route, we can't call the before_filter method directly in my test case.

     

    So, To fix this problem...

    Create TestController in my_app/test/functional/application_controller_test.rb
    Append test route to application
    Setup @controller, @request objects [if required]

    For Example:(Rails 4.1.14.2 & ruby-2.1.7)

    my_app/Gemfile

    source 'https://rubygems.org'
    gem 'browsernizer'
    group :test do gem 'test-unit','~>2.5.0'
    end

     

    my_app/app/controllers/application_controller.rb

    class ApplicationController < ActionController::Base
     before_filter :other_filter_method
     before_filter :check_browser_support 
    
     def check_browser_support
      unless request.env['browsernizer']['supported']
          render :layout => browser_layout(params[:action]), :template => '/static/browser.html.erb'
      end
    end  
    private
    def browser_layout(my_action)
        if my_action =='index'
          'my_browser'
        end
     end
    end

    my_app/test/functional/application_controller_test.rb

    require 'test_helper'
    class TestController < ApplicationController
      def index; end
    end
    
    class ApplicationControllerTest < ActionController::TestCase
     MyApp::Application.routes.append do
        controller :test do
          get 'test/index' => :index
        end
      end
      MyApp::Application.routes_reloader.reload!
    
     def setup
      @controller = TestController.new
      @request = ActionController::TestRequest.new
      @request.env['browsernizer'] = {}
      @request.env['browsernizer']['support'] = false
     end
    
     test "it should redirect to my_browser page" do
       params = {:action=> 'index' }
       get :index, params
       assert layout: my_browser
       assert_template 'static/browser.html.erb'
     end
    end

     

    Run your Test Case using command ...
    ruby -I "lib:test" test/functional/application_controller_test.rb

     

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: