如何在Ruby on Rails和Test :: Unit上测试Controllerfilter

我们在Ruby on Rails中有一个包含许多filter的大型应用程序。 其中一些filter可能很复杂。 我正在寻找一种通过unit testing单独测试这些滤波器的方法。 现在我通过一个使用function测试的动作测试它们来测试它们。 这只是感觉不对劲。
有没有人有这方面的建议或经验?

请记住,filter只是一种方法。
鉴于这种:

class SomeController before_filter :ensure_awesomeness ... end 

没有理由你不能这样做:

 SomeController.new.ensure_awesomeness 

然后检查它是否调用redirect_to或它应该做的任何事情

我有一篇关于before_filters的unit testing的post很容易,你不妨看看。 希望它会有所帮助。

您可以使用以下代码进行测试:

 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

猎户座我曾经在几次事件中搞砸了。 此外,大多数时间filter是私有的,所以你必须发送:

 SomeController.new.send(:some_filter) 

我遇到过这个问题。

那些执行需要请求的操作的filter呢。 即使用Flash

作为Authlogic的示例,require_user方法不能仅使用ApplicationController.new.send(:some_filter)。

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

任何人都有一些关于如何孤立地测试这种东西的非黑客想法? (我是通过创建一个仅用于测试的额外虚拟控制器来实现的。)

这取决于您的filter正在做什么。

这: http : //movesonrails.com/journal/2008/1/23/testing-your-application-controller-with-rspec.html

而且学习如何使用摩卡也会让你走得更远。