【问题标题】:RSpec tests for custom username routes are failing自定义用户名路由的 RSpec 测试失败
【发布时间】:2012-02-27 01:01:34
【问题描述】:

我有一个与这样的用户名匹配的受限路由:

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

【问题讨论】:

    标签: ruby-on-rails routing rspec routes custom-routes


    【解决方案1】:

    在您的路由定义中使用:constraints => {...}

    您传递的参数太多...

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

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

    【讨论】:

      猜你喜欢
      • 2014-08-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多