使用Minitest测试助手方法

时间:2014-03-05 02:12:57

标签: ruby-on-rails-4 devise minitest

我想使用 Minitest minitest-rails)来测试辅助方法 - 但辅助方法取决于current_user, a Devise helper method available to controllers and view

应用/助手/ application_helper.rb

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

测试/助手/ 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

请注意,我可以测试不依赖current_user的其他帮助方法。

1 个答案:

答案 0 :(得分:12)

在Rails中测试帮助程序时,帮助程序包含在测试对象中。 (测试对象是ActionView :: TestCase的一个实例。)您的助手的user_is_admin?方法期望名为current_user的方法也存在。在控制器和view_context对象上,此方法由Devise提供,但它不在您的测试对象上。让我们添加它:

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

current_user返回的对象取决于您。在这里,我们返回了一个数据夹具。您可以在此处返回任何在测试环境中有意义的对象。