我有一个匹配的路由,匹配这样的用户名:
controller :users, :path => '/:username', :as => :user, :constrain => { :username => /^_?[a-z]_?(?:[a-z0-9]_?)*$/i } do
# lots of nested routes go here
end
当我为此编写RSpec测试时(与正常使用user_id
相比),所有测试都失败了,因为它“无法找到路由”,即使它在服务器上正常工作。
describe "for an invalid request" do
it "should render a 404 if an associated photo is not found" do
# give it a bad photo id
xhr :post, :destroy, :id => "999999", :photo_id => "999999", :username => @photo_owner.username
# not found
response.status.should == not_found
end
end
当我在切换到用户名之前在路由中使用user_id
时,此测试工作正常:
resources :users do
# nested routes
end
和
xhr :post, :destroy, :id => "999999", :photo_id => "999999", :user_id => @photo_owner.id
那么我做错了什么,改变了什么?
我的服务器控制台显示了这一点,这意味着我应该正确传递所有参数:
Processing by TagsController#destroy as JS
Parameters: {"constrain"=>{"username"=>/^_?[a-z]_?(?:[a-z0-9]_?)*$/i}, "username"=>"rubynewb", "photo_id"=>"2004-the-title-of-the-photo-here", "id"=>"1797"}
答案 0 :(得分:2)
在路线定义中使用:constraints => {...}
。
你传递的参数太多了......
"constrain"=>{"username"=>/^_?[a-z]_?(?:[a-z0-9]_?)*$/i}
Rails无法识别:constrain
,因此它和它的内容作为参数传递,而不是由Rails路由器处理。