用Minitest测试助手方法 [英] Test helper method with Minitest
问题描述
我想使用 Minitest 测试一个帮助方法( minitest-rails
) - 但辅助方法取决于 current_user
,可用于控制器和视图的Devise助手方法。
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 p>
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
请注意,我能够测试不依赖 current_user
的其他帮助方法。
Note that I am able to test other helper methods that do not rely on current_user
.
推荐答案
你在Rails中测试一个助手,帮助器被包含在测试对象中。 (测试对象是ActionView :: TestCase的一个实例)您的帮助者的 user_is_admin?
方法期待一个名为 current_user
也存在。在控制器和view_context对象上,此方法由Devise提供,但它不在您的测试对象上。我们来补充一下:
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
current_user返回的对象
取决于您。在这里我们返回了一个数据夹具。您可以在这里返回任何在您测试的上下文中有意义的对象。
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.
这篇关于用Minitest测试助手方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!