在我的Rails应用程序中,我需要一种非常快速的方法来阻止包含特定查询字符串值的请求。我能够在使用高级约束的路线中执行此操作。它在现实世界中运行良好,但我无法弄清楚如何为它编写测试。
这是我的routes.rb中的代码:
class BlockedConstraint
@@block_ids = []
@@block_ids << '12345'
@@block_ids << '67890'
def self.matches?(request)
@@block_ids.include?(request.query_parameters["app_id"])
end
end
namespace :api do
match "*path" => "block#block_request", :constraints => BlockedConstraint
match 'ads' => 'status#get_status', :via => :get
match 'init' => 'init#get_init', :via => :get
#etc.
end
这是我的规格:
describe "BlockController" do
it "blocks app_id 12345" do
{ :get => 'api/status', :app_id => '12345' }.should route_to(
:controller => 'api/block',
:action => 'block_request'
)
end
end
但是我收到了这个错误:
Failure/Error: { :get => 'api/status', :app_id => '12345' }.should route_to(
Test::Unit::AssertionFailedError:
The recognized options <{"action"=>"get_status", "controller"=>"api/status"}> did not match <{"action"=>"block_request", "controller"=>"api/block"}>, difference: <{"action"=>"block_request", "controller"=>"api/block"}>
我也在路由/ routes_spec.rb中尝试了它,并描述了路由。结果相同。 (我实际上不确定是否最好将它与路由规范或控制器规格一起使用。)
我正在运行Rails 3.0.10和Rspec 2.11.0。
答案 0 :(得分:0)
在使用route_to测试之前,我从未测试过约束,但可能是匿名控制器可能对您的测试有用。
https://www.relishapp.com/rspec/rspec-rails/v/2-4/docs/controller-specs/anonymous-controller
您可以为应用程序控制器编写规范,例如:
require 'spec_helper'
describe ApplicationController do
controller do
def index
end
end
describe 'handling block constraints' do
before { get :index, :app_id => '100' }
it "should block request" do
should redirect_to(:controller => 'blocks', :action => 'block_request')
end
end
end