How to test helpers in Rails with Devise current_user and ActionView::TestCase

Chris Oliver

December 2, 2019

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.

P.S. You might enjoy following me on Twitter.


Comments

Want to stay up-to-date with Ruby on Rails?

Join 76,990+ developers who get early access to new tutorials, screencasts, articles, and more.

    We care about the protection of your data. Read our Privacy Policy.

    Screencast tutorials to help you learn Ruby on Rails, Javascript, Hotwire, Turbo, Stimulus.js, PostgreSQL, MySQL, Ubuntu, and more. Icons by Icons8

    © 2023 GoRails, LLC. All rights reserved.