ruby-on-rails-4 – 使用Minitest测试辅助方法

前端之家收集整理的这篇文章主要介绍了ruby-on-rails-4 – 使用Minitest测试辅助方法前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我想使用Minitest( @L_301_0@)测试辅助方法 – 但辅助方法取决于 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的方法也存在.在控制器和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返回的对象取决于您.在这里,我们返回了一个数据夹具.您可以在此处返回任何在测试环境中有意义的对象.

原文链接:https://www.f2er.com/ruby/267108.html

猜你在找的Ruby相关文章