【问题标题】:Rails: Moving a helper method form a test to test_helper.rbRails:将辅助方法从测试移动到 test_helper.rb
【发布时间】:2014-08-26 21:07:47
【问题描述】:

我正在尝试将辅助方法从控制器测试移动到 test_helper.rb:

# example_controller_test.rb
require 'test_helper'
class ExampleControllerTest < ActionController::TestCase
  should 'get index' do
    turn_off_authorization
    get :show
    assert_response :success
  end
end

# test_helper.rb
class ActionController::TestCase
  def turn_off_authorization
    ApplicationController.any_instance
                         .expects(:authorize_action!)
                         .returns(true)
  end
end

但是,我收到一个错误:

NameError: undefined local variable or method `turn_off_authorization' for #<ExampleControllerTest:0x000000067d6080>

我做错了什么?

【问题讨论】:

    标签: ruby-on-rails testing minitest


    【解决方案1】:

    原来我不得不将辅助方法包装到一个模块中:

    # test_helper.rb
    class ActionController::TestCase
      module CheatWithAuth do
        def turn_off_authorization
          # some code goes here
        end
      end
    
      include CheatWithAuth
    end
    

    我仍然不知道为什么原来的版本不起作用。

    这个想法来自另一个答案: How do I write a helper for an integration test in Rails?

    编辑:另一个解决方案刚刚来自我的朋友:

    # test_helper.rb
    class ActiveSupport::TestCase
      def turn_off_authorization
        # some code goes here
      end
    end
    

    注意这里使用的是ActiveSupport::TestCase(不是ActionController::TestCase)。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-03-06
      • 1970-01-01
      • 2013-05-11
      • 2010-12-24
      • 1970-01-01
      • 1970-01-01
      • 2012-12-30
      • 2016-07-22
      相关资源
      最近更新 更多