【问题标题】:Rspec for routes using advanced constraint on querystring?对查询字符串使用高级约束的路由的 Rspec?
【发布时间】:2012-09-26 00:25:07
【问题描述】:

在我的 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。

【问题讨论】:

  • 尝试将 app_id 烘焙到路径中的路由规范,例如{ :get =&gt; 'api/status?appid=12345' }
  • 这给了我同样的错误。 :-(

标签: ruby-on-rails rspec rspec-rails


【解决方案1】:

在使用 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

【讨论】:

  • 仅供参考,@oivoodoo 和我都试过了,但它不起作用。还有其他想法吗?
猜你喜欢
  • 2017-11-25
  • 2016-06-28
  • 2014-04-25
  • 2011-04-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-04-12
相关资源
最近更新 更多