ActionController :: UrlGenerationError - 在控制器中定义路由和操作,仍然没有路由错误

时间:2015-07-22 16:03:38

标签: ruby-on-rails rspec

运行我的schools_controller_spec.rb测试时,我在RSpec中收到以下错误:

ActionController::UrlGenerationError: No route matches {:action=>"show", :controller=>"schools"}

让我感到困惑的是,我配置了路由,并在相应的控制器中定义了操作。我没有在规范中的其他测试中收到此错误,例如'GET #index'等。使用RSpec / Capybara运行Rails 4.2。

这里是routes.rb:

Rails.application.routes.draw do
  root to: 'pages#home', id: 'home'
  resources :users
  resources :schools
  resource :session, only: [:new, :create, :destroy]
  match '/home',      to: 'pages#home', via: 'get', as: 'home_page'
end

rake routes返回:

    schools GET    /schools(.:format)          schools#index
            POST   /schools(.:format)          schools#create
 new_school GET    /schools/new(.:format)      schools#new
edit_school GET    /schools/:id/edit(.:format) schools#edit
     school GET    /schools/:id(.:format)      schools#show
            PATCH  /schools/:id(.:format)      schools#update
            PUT    /schools/:id(.:format)      schools#update
            DELETE /schools/:id(.:format)      schools#destroy

在第五行定义了路线,就像学校#show。

schools_controller.rb:

class SchoolsController < ApplicationController
  before_action :require_signin
  before_filter :admin_only, except: :index, :show

  def index
    @schools = School.all
  end

  def show
   # code pending
  end

  private

    def admin_only
      unless current_user.admin?
        redirect_to :back, alert: "Access denied."
      end
    end
end

单个学校的链接似乎在视图助手(_school.html.haml)中正确定义:

%li#schools
  = link_to school.name, school
  = school.short_name
  = school.city
  = school.state

并查看前端HTML确认它正常工作。我可以看到,例如:<a href="/schools/1">Community College of the Air Force</a>。当我单击该链接时,该页面在调试转储中显示以下内容:

--- !ruby/hash:ActionController::Parameters
controller: schools
action: show
id: '1'

最后,为了更好的衡量,这里是spec文件(schools_controller_spec.rb):

require 'rails_helper'

describe SchoolsController, type: :controller do
  # specs omitted for other actions

  describe 'GET #show' do
    context "when not signed in" do
      it "returns a 302 redirect code" do
        get :show
        expect(response.status).to eq 302
      end

      it "redirects to the signin page" do
        get :show
        expect(response).to redirect_to new_session_path
      end
    end

    context "when signed in as user" do
      before :each do
        @user = double(:user)
        allow(controller).to receive(:current_user).and_return @user
        @school = create(:school)
      end

      it "assigns the school to the @school variable" do
        get :show
        expect(assigns(:school)).to eq @school
      end
    end
  end
end

该路线出现在佣金路线中。该方法在适当的控制器中定义。似乎没有任何愚蠢的命名错误(例如复数/单数)。例如,规范似乎没有任何问题路由GET #index或其他路由。一切都在浏览器中按预期正常完成

那么为什么我要继续得到&#34;没有路线匹配&#34;运行控制器规范时出错?

1 个答案:

答案 0 :(得分:1)

这是因为show动作期待你目前没有通过的id。替换:

get :show

有了这个:

get :show, id: school.id

以上假设你有一个学校变量,也许是一个允许在前一个块?

let(:school) { create(:school) }