簡體   English   中英

如何在Ruby on Rails中測試控制器過濾器和Test :: Unit

[英]How to test Controller Filters in Ruby on Rails and Test::Unit

我們在Ruby on Rails中有一個帶有許多過濾器的大型應用程序。 其中一些過濾器可能很復雜。 我正在尋找一種通過單元測試分別測試這些過濾器的方法。 現在,我通過使用將它們與功能測試結合使用的操作來對它們進行測試。 這只是感覺不正確。
有人對此有意見或經驗嗎?

請記住,過濾器只是一種方法。
鑒於這種:

class SomeController
  before_filter :ensure_awesomeness

  ...
end

您沒有理由不能僅僅這樣做:

SomeController.new.ensure_awesomeness

然后檢查它是否調用redirect_to或應該執行的任何操作

您可以使用以下代碼進行測試:

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

我有一篇關於單元測試before_filters 的文章 ,您不妨看一看。 希望它會有所幫助。

這取決於您的過濾器在做什么。

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

並且學習如何使用摩卡咖啡將使您大有收獲。

Orion在幾次情況下我都無法做到這一點。 另外,大多數時間過濾器都是私有的,因此您必須發送:

SomeController.new.send(:some_filter)

我遇到了這個問題。

關於執行需要請求的操作的過濾器呢? 即使用Flash

僅使用ApplicationController.new.send(:some_filter)不能成為Authlogic require_user方法的示例。

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

有人對如何單獨測試這種東西有一些非駭客的想法嗎? (我通過創建一個僅用於測試的額外虛擬控制器來做到這一點。)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM