在Rails中测试ApplicationController的before_filter

4
我有一个应用程序,它可以检测请求中的子域并将结果设置为变量。
例如:
before_filter :get_trust_from_subdomain

def get_trust_from_subdomain
  @selected_trust = "test"
end

我该如何使用Test::Unit / Shoulda测试这个?我没有看到进入ApplicationController并查看设置的方法...
3个回答

1

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

before_filter 在我的应用控制器中 - 或者您是建议我为此测试设置一个专门的控制器? - Neil Middleton
完全不需要。您可以直接将过滤器放在ApplicationController中,测试应该仍然有效。FooController只是一个说明性的例子。此外,任何直接或间接继承ApplicationController的控制器都将继承此过滤器行为,并且您可以在任何相关的控制器功能测试中进行测试。 - Richard Cook
抱歉挖起一个旧的帖子,但我也一直在尝试这个。因此,测试 ApplicationController 中定义的 before_filter 最简单的方法是将它们作为派生控制器的测试的一部分来测试吗? - pjmorse
我认为是这样的。你可能会创建一个测试控制器类,从ApplicationController派生,仅在测试代码的上下文中可用,专门用于此目的。 - Richard Cook

0

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

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

0

ApplicationController 是全局的,你考虑过写一个 Rack 中间件吗?测试起来更容易。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接