11

I would like to test a helper method using Minitest (minitest-rails) - but the helper method depends on current_user, a Devise helper method available to controllers and view.

app/helpers/application_helper.rb

def user_is_admin?                           # want to test
  current_user && current_user.admin?
end

test/helpers/application_helper_test.rb

require 'test_helper'

class ApplicationHelperTest < ActionView::TestCase
  test 'user is admin method' do
    assert user_is_admin?                # but current_user is undefined
  end
end

Note that I am able to test other helper methods that do not rely on current_user.

Juanito Fatas
  • 9,419
  • 9
  • 46
  • 70
user664833
  • 18,397
  • 19
  • 91
  • 140

1 Answers1

15

When you test a helper in Rails, the helper is included in the test object. (The test object is an instance of ActionView::TestCase.) Your helper's user_is_admin? method is expecting a method named current_user to also exist. On the controller and view_context objects this method is provided by Devise, but it is not on your test object, yet. Let's add it:

require 'test_helper'

class ApplicationHelperTest < ActionView::TestCase
  def current_user
    users :default
  end

  test 'user is admin method' do
    assert user_is_admin?
  end
end

The object returned by current_user is up to you. Here we've returned a data fixture. You could return any object here that would make sense in the context of your test.

Juanito Fatas
  • 9,419
  • 9
  • 46
  • 70
blowmage
  • 8,854
  • 2
  • 35
  • 40
  • 1
    Thanks for the extra info in your answer! And thanks a lot for `minitest-rails`!! What terminology (like *stubbing*) would you use here, for what we are doing to `current_user`? By the way, I made `current_user` a `private` method, and I am using a global variable (`@admin = false`) in `ApplicationHelperTest` to control what `current_user` returns (`FactoryGirl.create(@admin ? :admin : :user)`) -- so I set `@admin = true` when I want to alter the behaviour, and I set it back when I'm done. – user664833 Mar 05 '14 at 07:31
  • I don't have any terminology for it. It's just a method. Your helper method has a dependency on it existing. – blowmage Mar 05 '14 at 13:34
  • +1 for mentioning that Helpers have to be tested as an instance from ActionView::TestCase. I am used to rspec and forget that always ;-) – awenkhh Sep 04 '15 at 13:59