2013-10-09 29 views
0

在我的一些控制器的使用設計的CURRENT_USER我需要使用屬於我的登錄用戶(current_user.groups)的組(S)。當我嘗試測試時;我似乎沒有這個current_user雖然:在試驗單位

ActionView::Template::Error: undefined method `authenticate' for nil:NilClass 

所以我想我應該創建設計出CURRENT_USER。

我讀過制定的,說明我應該添加以下到我的test_helper.rb中文檔:

class ActionController::TestCase 
    include Devise::TestHelpers 
    def setup 
     @request.env["devise.mapping"] = Devise.mappings[:user] 
     sign_in FactoryGirl.create(:user) 
    end 
end 

這似乎並不雖然做的伎倆;每當我跑rake test我得到以下錯誤:

1) Error: 
ActivitiesControllerTest#test_should_create_activity: 
NameError: uninitialized constant ActionController::TestCase::FactoryGirl 
    test/test_helper.rb:22:in `setup' 
+0

你已包括在你的Gemfile的測試組中的factory_girl_rails寶石? – Richard

+0

我是假設它來與設計的寶石。由於整個登錄/註冊事情在我的應用程序中像一個魅力。 – CaptainCarl

+0

比爲什麼不我需要它正常登錄? – CaptainCarl

回答

3

您必須在您的Gemfile的factory_girl_rails寶石。我通常將它包含在開發和測試組中,但只是測試環境對您的示例而言很好。

group :development, :test do 
    gem 'factory_girl_rails' 
end 

然後運行bundle install

sign_in FactoryGirl.create(:user)

然後,你需要創建一個工廠(這幾乎就像一個夾具):

rails generate factory_girl:model user

當你創建你的測試用戶夾具

factory_girl_rails使用

這將創建文件:test/factories/users.rb

R EAD更多關於factory_girl_rails以及如何在這裏定義的工廠:https://github.com/thoughtbot/factory_girl_rails

+0

它引發了我:'PictogramsControllerTest#test_should_update_pictogram: 參數錯誤:工廠未註冊:用戶 測試/ test_helper.rb:21:在'setup'' – CaptainCarl

+0

我已經更新了我的答案,我認爲這應該夠了。 – Richard

+0

訣竅。謝謝 – CaptainCarl