-->

Test helper method with Minitest

2019-03-27 13:23发布

问题:

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.

回答1:

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.