Writing test code for ApplicationController

Did you ever try to write functional test code for ApplicationController? You might have faced such situations where you needed to test some methods of your application controller. Well when you will start testing a method of your ApplicationController, you would probably have a "aha" moment - "If I had a view file for that method!!". Yes the problem is template missing error. 
Usually the methods in ApplicationController dont have a corresponding template. Therefore, sending test request to those methods will definitely raise an ActionView::MissingTemplate error. So what you need to do is just tell the ApplicationController - "Please dont raise any template missing exception. I am testing your methods :)".
But how will you tell this? Simple, just override the rescue_action method and raise nothing!! Just like the following:

class ApplicationController
    def rescue_action(e)
    end
end
Yes, this will keep all the exceptions away from you. However, we only need to handle MissingTemplate exception, not anything else. And its easy, isnt it?? You must have already pictured the following:
class ApplicationController
    def rescue_action(e)
        raise e unless e.is_a?(ActionView::MissingTemplate)
    end
end

Hmm, you know what!! I am little more fashionable in terms of writing code. Think how it will be if we can tell my ApplicationControllerTest class which exception classes to be ignored? like
class ApplicationControllerTest < ActionController::TestCase
    ignore_exceptions(ActionView::MissingTemplate)
    def test_user_load do
        get :load_user
        assert_not_nil(assigns(:user))
    end
end

Did you like the way? If so then lets make the whole...
class ApplicationController
    @@exception_classes = []
    def self.set_ignorable_exceptions(classes)
        @@exception_classes = classes
    end
    def rescue_action(e);raise e unless @@exception_classes.include?(e.class); end
end

module ActionController
    class TestCase
        class << self
            def ignore_exceptions(*classes)
                ApplicationController.set_ignorable_exceptions(classes)
            end
        end
    end
end

And now! Yes, now you just tell your test class that which exception classes to be ignored and see how obedient it is!!

Well if you have any more stylish suggestion you are most welcome to share :)

Comments

Popular posts from this blog

Ajax form submission with tiny MCE editor

Samsung BADA, Starting with sample application

Bada tutorial: Application basics