Ruby on rails 4 带有Minitest的测试辅助方法
我想使用Minitest()测试助手方法,但助手方法取决于 app/helpers/application\u helper.rbRuby on rails 4 带有Minitest的测试辅助方法,ruby-on-rails-4,devise,minitest,Ruby On Rails 4,Devise,Minitest,我想使用Minitest()测试助手方法,但助手方法取决于 app/helpers/application\u helper.rb def user_is_admin? # want to test current_user && current_user.admin? end require 'test_helper' class ApplicationHelperTest < ActionView::TestC
def user_is_admin? # want to test
current_user && current_user.admin?
end
require 'test_helper'
class ApplicationHelperTest < ActionView::TestCase
test 'user is admin method' do
assert user_is_admin? # but current_user is undefined
end
end
test/helpers/application\u helper\u test.rb
def user_is_admin? # want to test
current_user && current_user.admin?
end
require 'test_helper'
class ApplicationHelperTest < ActionView::TestCase
test 'user is admin method' do
assert user_is_admin? # but current_user is undefined
end
end
需要“测试助手”
类ApplicationHelperTest
请注意,我可以测试不依赖于当前用户的其他帮助器方法。在Rails中测试帮助器时,该帮助器包含在测试对象中。(测试对象是ActionView::TestCase的一个实例。)您的助手的
用户\u is\u admin?
方法希望名为当前用户的方法也存在。在控制器和视图上下文对象上,此方法由Desive提供,但尚未在测试对象上提供。让我们补充一下:
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
需要“测试助手”
类ApplicationHelperTest
当前用户返回的对象由您决定。这里我们返回了一个数据装置。您可以在此处返回在测试上下文中有意义的任何对象。感谢您在回答中提供的额外信息!非常感谢minitest rails
!!对于我们对当前用户所做的工作,您会在这里使用什么术语(如存根)?顺便说一下,我创建了current_user
一个private
方法,并在ApplicationHelperTest
中使用一个全局变量(@admin=false
)来控制current_user
返回的内容(FactoryGirl.create(@admin?:admin::user)
)--因此,当我想改变行为时,我会设置@admin=true
,当我完成时,我会将其设置回原来的状态。我没有任何术语。这只是一种方法。您的helper方法对它存在依赖性。+1表示helper必须作为ActionView::TestCase中的实例进行测试。我习惯于抱怨,却总是忘记;-)