我想使用 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
的其他帮助方法。
答案 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
返回的对象取决于您。在这里,我们返回了一个数据夹具。您可以在此处返回任何在测试环境中有意义的对象。