Test helper method with Minitest

梦想的初衷 提交于 2019-12-04 21:28:14

问题


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.



来源:https://stackoverflow.com/questions/22187127/test-helper-method-with-minitest

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!