鉴于数据库中的几个城市:
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
在这里,我希望它通过,但它失败了。
规范中似乎忽略了约束,因为匹配的城市与坏城市的行为相同。
这是一个已知问题,还是我遗漏了一些我需要做的事情?
最佳答案
这种方法有效:
在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
最后,我添加了一个观察者来在城市表发生变化时重新加载路线。
关于ruby-on-rails - 如何使用 RSpec 测试路由约束,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3856322/