我有一个应用程序可以检测请求中的子域并将结果设置为变量。
例如
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')
给定一个 Controller
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
中,然后任何派生 Controller 也将继承此过滤器行为: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
关于ruby-on-rails - 在 Rails 中测试 ApplicationController before_filter,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/3762080/