Mocking authentication - Ramaze/ramaze GitHub Wiki

Sometimes, you need to pretend a user is logged to be able to test some parts of your application where a user needs to be loged in.

For this, you need to mock authentication.

It can be done quite simply by re-opening the UserHelper class, replacing #logged_in? and #user methods.

However, if you leave the class with the overriden methods, all specs that will run after (even in other files) will get the new always-authenticated behaviour.

Thus, you have to restore the class to it's original state when you don't need to fake the authentication anymore. It's a good idea to always do this at the end of spec file that change the UserHelper class.

For instance, your spec file could look like this :

# Let's override #user and #logged_in?
module Ramaze
  module Helper
    module UserHelper
      # This will be our new implementation for 'logged_in?'
      # that always says 'yes, this guy is logged in'
      def fake_logged_in?
        true
      end

      # This will be our new implementation for 'user'
      # that will return a guinea pig logged in user
      def fake_user
        User[:email=>'[email protected]']
      end

      # We alias the initial 'logged_in?' method so we can restore it later
      alias real_logged_in? logged_in?

      # And replace it with our faked 'logged_in?' method
      alias logged_in? fake_logged_in?

      # We alias the initial 'user' method so we can restore it later
      alias real_user user

      # And replace it with our faked 'user' method
      alias user team_user
    end
  end
end

# many specs here that require to be authenticated
#

#
# All specs are done here; we need to restore the
# class to it's original state
module Ramaze
  module Helper
    module UserHelper
      # Restore original 'logged_in?' and 'user' methods
      alias logged_in? real_logged_in?
      alias user real_user
    end
  end
end