【问题标题】:How do you test route constraints using RSpec如何使用 RSpec 测试路由约束
【发布时间】:2011-04-20 20:34:10
【问题描述】:

给定数据库中的几个城市:

City.first.attributes => {:id => 1, :name => 'nyc'}
City.last.attributes =>  {:id => 2, :name => 'boston'}

还有这样的路线:

match '/:city/*dest' => 'cities#do_something', :constraints => {:city => /#{City.all.map{|c| c.name}.join('|'}/}

(因此约束应计算为:/nyc|boston/)

还有一个规范:

it "recognizes and generates a route for city specific paths" do
  { :put => '/bad-city/some/path' }.should route_to({:controller => "cities", :action => "do_something", :dest => 'some/path', :city => 'bad-city'})
end

我预计会失败。但它通过了。

同样:

it "doesn't route bad city names" do
  { :put => '/some-bad-city/some/path' }.should_not be_routable
end

在这里我希望它通过,但它失败了。

规范中似乎忽略了约束,因为匹配的城市与不良城市具有相同的行为。

这是一个已知问题,还是我错过了一些我需要做的事情?

【问题讨论】:

  • 因为这适用于开发,但不适用于测试,我认为问题是在启动时评估约束,并且在测试数据库中当时没有城市。所以正则表达式看起来像 //,并且匹配所有内容。但是,当我尝试将其设为 Proc 或实现 #matches?(request) 的类时,它似乎永远不会被调用。

标签: ruby-on-rails routing ruby-on-rails-3 rspec constraints


【解决方案1】:

这种方法有效: 在routes.rb中

match '/:city/*destination' => 'cities#myaction', :constraints => {:city => /#{City.all.map{|c|c.slug}.join('|')}/}

在规范中:

describe "routing" do
  before(:each) do
    @mock_city = mock_model(City, :id => 42, :slug => 'some-city')
    City.stub!(:find_by_slug => @mock_city, :all => [@mock_city])
    MyApp::Application.reload_routes!
  end

  it "recognizes and generates a route for city specific paths" do
    { :get => '/some-city/some/path' }.should route_to({:controller => "cities", :action => "myaction", :destination => 'some/path', :city => 'some-city'})
  end

  it "rejects city paths for cities that don't exist in the DB" do
    { :get => '/some-bad-city/some/path' }.should_not be_routable
  end
end

最后,我添加了一个观察者,以便在城市表发生变化时重新加载路线。

【讨论】:

  • 像这样使用 db find all in the routes.rb 太可怕了。在这种情况下,控制器或 before_filter 应该验证城市。
【解决方案2】:

指定约束时,必须包含要约束的参数:

match '/:city/*dest' => 'cities#do_something', :constraints => { :city => /nyc|boston|philly/ }

【讨论】:

  • 你知道 - 在我试图简化问题时,我引入了一个错字。谢谢你的收获。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-12-18
  • 1970-01-01
  • 2011-08-21
  • 2011-08-04
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多