Ruby on rails 在Rails中过滤之前测试ApplicationController

Ruby on rails 在Rails中过滤之前测试ApplicationController,ruby-on-rails,functional-testing,Ruby On Rails,Functional Testing,我有一个应用程序,可以在请求中检测子域并将结果设置为变量 e、 g 我如何使用test::Unit/Shoulda来测试它?我看不到进入ApplicationController并查看设置内容的方法…该方法应允许您查询@selected\u trust的值。断言其值等于“test”,如下所示: assert_equal 'test', assigns('selected_trust') 给定一个控制器foo_controller.rb class FooController < Appl

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

e、 g

我如何使用test::Unit/Shoulda来测试它?我看不到进入ApplicationController并查看设置内容的方法…

该方法应允许您查询
@selected\u 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
与注释相关:请注意,过滤器可以放置在
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
class ApplicationController“Hello world”
结束
结束

应用程序控制器是全局的,您是否考虑过编写机架中间件?更容易测试。

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

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
需要“测试助手”
类HomeControllerTest
before_过滤器在我的应用程序控制器中-或者你是建议我专门为此测试设置一个控制器?一点也不。您可以直接将过滤器放入
ApplicationController
中,测试也应该是一样的
FooController
只是一个示例。此外,任何直接或间接将ApplicationController子类化的控制器都将继承此筛选器行为,您可以在任何相关的控制器功能测试中对其进行测试。很抱歉,拖出一个旧线程,但我也一直在处理此问题。因此,在
ApplicationController
中定义的过滤器之前测试
最简单的方法就是将它们作为一个派生控制器测试的一部分进行测试?我认为是这样的。您可能会创建一个从
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
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