运行控制器规范(rspec)时出现路由错误

时间:2012-03-04 04:09:13

标签: ruby-on-rails routing rspec

我觉得我在routes.rb,我的控制器和我的控制器规范中都有我需要的一切,但由于某种原因,我仍然遇到路由错误(ActionController :: RoutingError)。这是我的控制器:

class HunchController < ActionController::Base
  protect_from_forgery

  def results
    auth_token_key = params[:auth_token_key]
    user_id = params[:user_id]
    @user = User.create!
    @user.auth_token = @user.get_auth_token(auth_token_key, user_id)
    @recommended_books = @user.get_recommended_books(@user.auth_token)
  end
end

这是我的控制器规范:

require 'spec_helper'

describe HunchController do
  describe "POST 'results'" do
    before do
      @params = {
        :auth_token_key => "my auth token",
        :user_id => "my user id"
      }
    end

    it "succeeds" do
      post :results, @params
      response.should be_success
    end
  end
end

这是我的routes.rb:

MyApplicationName::Application.routes.draw do
  root :to => 'hunch#index'

  resources :users
  post 'hunch/results' => "hunch#results"
  match '/results' => 'hunch#results'
end

编辑:这是我的佣金路线输出:

         root        /                         {:controller=>"pages", :action=>"index"}
hunch_results POST   /hunch/results(.:format)  {:controller=>"hunch", :action=>"results"}
      results        /results(.:format)        {:controller=>"hunch", :action=>"results"}
        users GET    /users(.:format)          {:action=>"index", :controller=>"users"}
              POST   /users(.:format)          {:action=>"create", :controller=>"users"}
     new_user GET    /users/new(.:format)      {:action=>"new", :controller=>"users"}
    edit_user GET    /users/:id/edit(.:format) {:action=>"edit", :controller=>"users"}
         user GET    /users/:id(.:format)      {:action=>"show", :controller=>"users"}
              PUT    /users/:id(.:format)      {:action=>"update", :controller=>"users"}

编辑#2:我的用户#show test也出现了这个错误。这是实际的错误:

  1) UsersController#show succeeds
     Failure/Error: get :show
     ActionController::RoutingError:
       No route matches {:controller=>"users", :action=>"show"}
     # ./spec/controllers/users_controller_spec.rb:13:in `block (3 levels) in <top (required)>'

1 个答案:

答案 0 :(得分:0)

好的,当宝石之旅更新到最新版本时,我遇到了同样的问题。如果你有这样的路线,那就找到它:

user GET    /users/:id(.:format)      {:action=>"show", :controller=>"users"}

有一个param(在本例中为id),一定需要在模板中呈现链接或在控制器中使用user_path / user_url变量 with param too ,所以在你的模板中试着找到:

<%= link_to "linkname", user_path %>

并替换为

<%= link_to "linkname", user_path(@user) %>

或在任何控制器中搜索user_path / user_url用法,并相应地将其替换为user_path(@user) / user_url(@user)