I’ve read a lot about Dependency Injection in Ruby and Rails lately, and thought I would do a quick post to showcase how Dependency Injection can really help you with even small methods. Such as testing the common current_user method in the ApplicationController:

Here is a quite simple method to authorize the current user by an Auth-Token variable, for API authentication.

def current_user(auth_token = request.headers['Auth-Token'])
  @current_user ||= Sessions::Tracker.authorize_and_access_by_auth_token!(request.headers['Auth-Token']).member

Now if we want to test this method directly, we have no option but to try and override the request headers in our test. This gets real messy real fast.

request.headers['Auth-Token'] = 'flum'
expect{controller.current_user}.to raise_error(NotSignedInError)

The above code doesn’t even work, and I am left to mess with the internals of the request, just because I want to get a bloody Auth token. Why? There must be a better way. There is! Dependency Injection to the rescue. The only real dependency here (apart from the Sessions::Tracker), is the request headers Auth Token. So let’s inject that dependency instead:

def current_user(auth_token = request.headers['Auth-Token'])
  @current_user ||= Sessions::Tracker.authorize_and_access_by_auth_token!(auth_token).member

Now the test becomes a piece of cake:

expect{controller.current_user('flum')}.to raise_error(NotSignedInError)

Of course we will also have to write tests for when sign in is succesful, but this should give you an idea of the power that is Dependency Injection