リクエストでサブドメインを検出し、結果を変数に設定するアプリケーションがあります。
例えば
before_filter :get_trust_from_subdomain
def get_trust_from_subdomain
@selected_trust = "test"
end
Test :: Unit / Shouldaでこれをテストするにはどうすればよいですか?ApplicationControllerに入り、何が設定されているかを確認する方法がわかりません...
リクエストでサブドメインを検出し、結果を変数に設定するアプリケーションがあります。
例えば
before_filter :get_trust_from_subdomain
def get_trust_from_subdomain
@selected_trust = "test"
end
Test :: Unit / Shouldaでこれをテストするにはどうすればよいですか?ApplicationControllerに入り、何が設定されているかを確認する方法がわかりません...
この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
ApplicationController
グローバルですが、代わりにラックミドルウェアを作成することを検討しましたか?テストがはるかに簡単です。
アプリケーションの別のコントローラーでこれを選択しました:
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