Recently I was trying to test a couple of helpers I had written in Rails. Basic helpers are pretty easily tested using ActionView::TestCase, but what happens when you want to use Devise' current_user
method in your helpers? We have to actually write our own method to stub out Devise current_user
in our test suite so that we can return the correct user.
Let's take a very trivial example of a helper that depends upon current_user
. Here we have a current_team
method that returns the first team for the user.
module ExampleHelper
def current_team
@current_team ||= current_user.teams.first
end
end
The current_resource method in Devise is not a helper, but a method in ApplicationController, so it's not available in ActionView::TestCase even if it was exposed with helper_method :current_user
in the controller.
To write tests for this, we need to actually implement the current_user
method in our test suite.
require 'test_helper'
class ExampleHelperTest < ActionView::TestCase
def current_user
@current_user
end
setup do
@current_user = users(:one)
end
test "current_team" do
assert_not_nil current_team
end
end
Everything is run in the context of our ActionView::TestCase
class, so the helpers have access to the methods inside our test suite.
What we've done here is defined the current_user
method and have it simply return an instance variable. This lets us change the value of current_user
at any time in our tests which can come in handy. Our test will call the current_team
helper, then call our current_user
method defined in ExampleHelperTest
and use that instead of the Devise method.