2008-10-30 236 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