鉴于数据库中的几个城市:
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
我希望它能通过,但失败了。
似乎规范中忽略了约束,因为匹配的城市与坏的城市具有相同的行为。
这是一个已知问题,还是我错过了我需要做的事情?
答案 0 :(得分:11)
这种方法有效: 在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
最后,我添加了一个观察者,以便在城市表发生变化时重新加载路线。
答案 1 :(得分:0)
指定约束时,必须包含要约束的参数:
match '/:city/*dest' => 'cities#do_something', :constraints => { :city => /nyc|boston|philly/ }