2008-10-30 133 views
1

我們在Ruby on Rails中有一個很大的應用程序,並帶有許多過濾器。其中一些過濾器可能很複雜。我正在尋找一種通過單元測試單獨測試這些過濾器的方法。現在我通過測試它們,通過在功能測試中使用它們的操作來測試它們。這只是感覺不到正確的方式。
有沒有人有此建議或經驗?如何在Ruby on Rails和測試中測試控制器過濾器::單元

回答

3

記住過濾器只是一種方法。
鑑於此:

class SomeController 
    before_filter :ensure_awesomeness 

    ... 
end 

沒有理由你不能只是這樣做:

SomeController.new.ensure_awesomeness 

,然後檢查它調用redirect_to的或是別的什麼應該做

0

獵戶我有在少數事件中與此相干。此外,大多數的時間篩選器是私人所以你必須做一個發送:

SomeController.new.send(:some_filter) 
1

a post單元測試before_filters輕鬆,你不妨去看看。希望它會有所幫助。

0

我遇到過這個問題。

如何執行需要請求的操作的過濾器。即使用閃存

示例是Authlogic require_user方法不會僅僅通過使用ApplicationController.new.send(:some_filter)而起作用。

https://github.com/binarylogic/authlogic_example/blob/master/app/controllers/application_controller.rb

人對如何在隔離測試這種事情一些非黑客的想法? (我通過創建一個額外的虛擬控制器,我只用於測試使用這樣做。)

1

您可以使用此代碼測試:

require "test_helper" 
describe ApplicationController do 

    context 'ensure_manually_set_password' do 
    setup do 
     class ::TestingController < ApplicationController 
     def hello 
      render :nothing => true 
     end 
     end 

     NameYourApp::Application.routes.draw do 
     get 'hello', to: 'testing#hello', as: :hello 
     end 
    end 

    after do 
     Rails.application.reload_routes! 
    end 

    teardown do 
     Object.send(:remove_const, :TestingController) 
    end 

    context 'when user is logged in' do 
     setup do 
     @controller = TestingController.new 
     end 

     context 'and user has not manually set their password' do 
     let(:user) { FactoryGirl.build(:user, manually_set_password: false) } 
     setup do 
        login_as user 
      get :hello 
     end 

     should 'redirect user to set their password' do 
      assert_redirected_to new_password_path(user.password_token) 
     end 
     end 
    end 
    end 
end 

它的代碼是從http://robots.thoughtbot.com/testing-a-before-filter原來, 我改變爲Rails 3