我有一个应用程序,它检测请求中的子域并将结果设置为变量。
e.g。
before_filter :get_trust_from_subdomain
def get_trust_from_subdomain
@selected_trust = "test"
end
如何用Test :: Unit / Shoulda测试?我没有看到进入ApplicationController并查看设置的方法......
答案 0 :(得分: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
答案 1 :(得分:0)
ApplicationController
是全球性的,您是否考虑过编写机架中间件?更容易测试。
答案 2 :(得分: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