我想使用测试辅助方法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
的其他辅助方法。
最佳答案
在Rails中测试助手时,该助手将包含在测试对象中。 (测试对象是ActionView::TestCase的实例。)您的助手的user_is_admin?
方法期望还存在一个名为current_user
的方法。在 Controller 和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
返回的对象由您决定。在这里,我们返回了一个数据夹具。您可以在此处返回在测试上下文中有意义的任何对象。
关于ruby-on-rails-4 - 使用Minitest的测试助手方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22187127/