2

在我的 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"}>

我还在 routing/routes_spec.rb 中尝试过,使用 describe Routing。结果相同。(我实际上不确定是否最好将其与路由规范或控制器规范一起使用。)

我正在运行 Rails 3.0.10 和 Rspec 2.11.0。

4

1 回答 1

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
于 2012-09-26T06:10:38.960 回答