4

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

例如

before_filter :get_trust_from_subdomain

def get_trust_from_subdomain
  @selected_trust = "test"
end

如何使用 Test::Unit / Shoulda 进行测试?我看不到进入 ApplicationController 并查看设置的方法...

4

3 回答 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
于 2010-09-21T15:58:31.783 回答
0

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

于 2010-09-21T16:15:39.397 回答
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
于 2010-09-21T16:31:26.710 回答