代码之家  ›  专栏  ›  技术社区  ›  Neil Middleton

在Rails中过滤之前测试ApplicationController

  •  4
  • Neil Middleton  · 技术社区  · 15 年前

    我有一个应用程序可以根据请求检测子域,并将结果设置为变量。

    例如

    before_filter :get_trust_from_subdomain
    
    def get_trust_from_subdomain
      @selected_trust = "test"
    end
    

    如何用test::unit/shoulda测试这个?我看不到进入应用程序控制器并查看设置内容的方法…

    3 回复  |  直到 15 年前
        1
  •  1
  •   Richard Cook    15 年前

    这个 assigns 方法应允许您查询 @selected_trust . 断言其值等于“test”,如下所示:

    assert_equal 'test', assigns('selected_trust')
    

    给一个控制器 foo_controller.rb

    class FooController < ApplicationController
      before_filter :get_trust_from_subdomain
    
      def get_trust_from_subdomain
        @selected_trust = "test"
      end
    
      def index
        render :text => 'Hello world'
      end
    end
    

    可以编写如下功能测试 foo_controller_test.rb :

    class FooControllerTest < ActionController::TestCase
      def test_index
        get :index
        assert @response.body.include?('Hello world')
        assert_equal 'test', assigns('selected_trust')
      end
    end
    

    与注释相关:请注意,过滤器可以放置在 ApplicationController 然后,任何派生的控制器也将继承这个过滤器行为:

    class ApplicationController < ActionController::Base
      before_filter :get_trust_from_subdomain
    
      def get_trust_from_subdomain
        @selected_trust = "test"
      end
    end
    
    class FooController < ApplicationController
      # get_trust_from_subdomain filter will run before this action.
      def index
        render :text => 'Hello world'
      end
    end
    
        2
  •  0
  •   Reactormonk    15 年前

    ApplicationController 是全局的,您是否考虑编写机架中间件?更容易测试。

        3
  •  0
  •   Neil Middleton    15 年前

    我在应用程序的另一个控制器中选择了此选项:

    require 'test_helper'
    
    class HomeControllerTest < ActionController::TestCase
    
      fast_context 'a GET to :index' do
        setup do
          Factory :trust
          get :index
        end
        should respond_with :success
    
        should 'set the trust correctly' do
          assert_equal 'test', assigns(:selected_trust)
        end
      end
    
    end