[英]Rails: Moving a helper method form a test to test_helper.rb
我試圖將一個輔助方法從控制器測試移動到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>
我究竟做錯了什么?
事實證明我必須將輔助方法包裝到模塊中:
# test_helper.rb
class ActionController::TestCase
module CheatWithAuth do
def turn_off_authorization
# some code goes here
end
end
include CheatWithAuth
end
我仍然不知道為什么原始版本不起作用。
這個想法來自另一個答案: 如何在Rails中為集成測試編寫幫助程序?
編輯 :另一個解決方案來自我的朋友:
# test_helper.rb
class ActiveSupport::TestCase
def turn_off_authorization
# some code goes here
end
end
請注意,此處正在使用ActiveSupport::TestCase
(不是ActionController::TestCase
)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.