如何使用RSpec测试路径约束

Mat*_*orn 5 routing rspec ruby-on-rails constraints ruby-on-rails-3

鉴于数据库中的几个城市:

City.first.attributes => {:id => 1, :name => 'nyc'}
City.last.attributes =>  {:id => 2, :name => 'boston'}
Run Code Online (Sandbox Code Playgroud)

还有一条路线:

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

(所以约束应该评估为:/ nyc |波士顿/)

一个规格:

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
Run Code Online (Sandbox Code Playgroud)

我希望失败.但它过去了.

同样:

it "doesn't route bad city names" do
  { :put => '/some-bad-city/some/path' }.should_not be_routable
end
Run Code Online (Sandbox Code Playgroud)

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

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

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

Mat*_*orn 11

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

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

在规范中:

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
Run Code Online (Sandbox Code Playgroud)

最后,我添加了一个观察者,以便在cities表更改时重新加载路由.

  • 使用db在find.rb中查找all是很可怕的.在这种情况下,控制器或before_filter应验证城市. (6认同)