2014-03-05 50 views
6

我想測試使用Minitestminitest-rails)的助手方法 - 但助手方法取決於current_user, a Devise helper method available to controllers and viewMinitest的測試助手方法

應用程序/傭工/ 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

回答

12

當您在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返回的對象取決於您。這裏我們已經返回了一個數據夾具。你可以在這裏返回任何對你測試環境有意義的對象。

+0

感謝您的答案中的額外信息!並且非常感謝'minitest-rails' !!你會在這裏使用什麼術語(比如* stubbing *),因爲我們對'current_user'做了什麼?順便說一下,我將'current_user'作爲'private'方法,並且在ApplicationHelperTest中使用全局變量('@admin = false')來控制'current_user'返回的內容('FactoryGirl.create(@admin? :admin::user)') - 所以當我想改變行爲時,我設置了'@admin = true',並在完成時將其設置回。 – user664833

+0

我沒有任何術語。這只是一種方法。你的幫助器方法依賴於它的存在。 – blowmage

+0

+1提及Helpers必須作爲ActionView :: TestCase的一個實例進行測試。我習慣於rspec並且忘記了那個;-) – awenkhh

相關問題