自定义用户名路由的RSpec测试失败

时间:2021-02-17 00:14:46

I have a constrained route that matches usernames like this:

我有一个与用户名匹配的受限路径:

controller :users, :path => '/:username', :as => :user, :constrain => { :username => /^_?[a-z]_?(?:[a-z0-9]_?)*$/i } do
   # lots of nested routes go here
end

When I go to write RSpec tests for this (versus using user_id like normal), all the tests are failing because it "can't find the route" even though it works fine on the server.

当我为它编写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

This test was working fine when I was using the user_id in my routes prior to switching to usernames:

在切换到用户名之前,我在路由中使用user_id时,这个测试运行良好:

resources :users do
  # nested routes
end

and

xhr :post, :destroy, :id => "999999", :photo_id => "999999", :user_id => @photo_owner.id

So what am I doing wrong and what has changed?

那么,我做错了什么,发生了什么变化?

My server console shows this which means I should have all of the parameters passed in properly:

我的服务器控制台显示了这一点,这意味着我应该将所有参数正确地传入:

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"}

1 个解决方案

#1


2  

Use :constraints => {...} in your route definition.

用途:约束= > {…在您的路径定义中。

You have one too many parameters being passed...

传递的参数太多了……

"constrain"=>{"username"=>/^_?[a-z]_?(?:[a-z0-9]_?)*$/i}

Rails doesn't recognize :constrain, therefore it and it's contents are passed along as a parameter instead of being processed by the Rails router.

Rails不识别:约束,因此它和它的内容作为参数传递,而不是由Rails路由器处理。

#1


2  

Use :constraints => {...} in your route definition.

用途:约束= > {…在您的路径定义中。

You have one too many parameters being passed...

传递的参数太多了……

"constrain"=>{"username"=>/^_?[a-z]_?(?:[a-z0-9]_?)*$/i}

Rails doesn't recognize :constrain, therefore it and it's contents are passed along as a parameter instead of being processed by the Rails router.

Rails不识别:约束,因此它和它的内容作为参数传递,而不是由Rails路由器处理。