2015-08-15 67 views
5

我在app/helpers/sessions_helper.rb中有一個幫助文件,其中包含一個方法my_preference,它返回當前登錄用戶的首選項。我想在集成測試中訪問該方法。例如,以便我可以在我的測試中使用get user_path(my_preference)如何在Rails集成測試中提供助手方法?

在其他的帖子我看了,這是通過在測試文件require sessions_helper可能的,但我仍然得到錯誤NameError: undefined local variable or method 'my_preference'。我究竟做錯了什麼?

require 'test_helper' 
require 'sessions_helper' 

class PreferencesTest < ActionDispatch::IntegrationTest 

    test "my test" do 
    ... 
    get user_path(my_preference) 
    end 

end 

回答

7

你的錯誤messagae說:

NameError: undefined local variable or method 'my_preference' 

,這意味着你不必my_preference方法訪問。要在班級中提供該模塊,您必須在課程中使用include模塊。

你必須在你的PreferencesTest課程中加入你的模塊:SessionsHelper

include SessionsHelper 

然後,將在您的測試中使用實例方法my_preference

所以,你想做的事:

require 'test_helper' 
require 'sessions_helper' 


class PreferencesTest < ActionDispatch::IntegrationTest 

    include SessionsHelper 

    test "my test" do 
    ... 
    get user_path(my_preference) 
    end 

end 
+0

謝謝,這有效!現在,如果我忽略'require'sessions_helper'',現在似乎也行得通。那有意義嗎?是否需要'sessions_helper'? – Marty

+0

是的,你不應該需要,如果它的'app/helpers'目錄下 讓我知道! –

1

如果有人想要在所有可用的測試特定的輔助方法,也可以包括在test_helper.rb文件助手模塊:

class ActiveSupport::TestCase 
... 
include SessionsHelper 
end 
相關問題