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 に答える