gpt4 book ai didi

ruby-on-rails - ActionController::UrlGenerationError:尝试测试 Controller 时没有路由匹配

转载 作者:数据小太阳 更新时间:2023-10-29 08:15:43 24 4
gpt4 key购买 nike

当我尝试测试目标 Controller 时,出现 ActionController::UrlGenerationError: No route matches (:action => "edit", :controller => "goals") 错误

这是我的 goals_controller_test.rb

require 'test_helper'

class GoalsControllerTest < ActionController::TestCase
test "should be redirected when not logged in" do
get :new
assert_response :redirect
assert_redirected_to new_user_session_path
end

test "should render the new page when logged in" do
sign_in users(:guillermo)
get :new
assert_response :success
end

test "should get edit" do
get :edit
assert_response :success
end

test "should get show" do
get :show
assert_response :success
end
end

这是我的routes.rb

Rails.application.routes.draw do
devise_for :users

authenticated :user do
root 'du#dashboard', as: "authenticated_root"
end

resources :goals

root 'du#Home'

end

我的goals_controller.rb

class GoalsController < ApplicationController
before_filter :authenticate_user!, only: [:new]

def new
end

def edit
end

def show
end

private

def find_user
@user = User.find(params[:user_id])
end

def find_goal
@goal = Goal.find(params[:id])
end
end

我觉得很奇怪,如果我使用 get 'goals/edit' 而不是 resources :goals 测试通过。

非常感谢您提供任何指南。

最佳答案

当您使用 resources :goals 时,Rails 会为您生成以下路由(RESTful):

    goals GET    /goals(.:format)          goals#index
POST /goals(.:format) goals#create
new_goal GET /goals/new(.:format) goals#new
edit_goal GET /goals/:id/edit(.:format) goals#edit
goal GET /goals/:id(.:format) goals#show
PATCH /goals/:id(.:format) goals#update
PUT /goals/:id(.:format) goals#update
DELETE /goals/:id(.:format) goals#destroy

如您所见,要点击 edit 操作 /goals/:id/edit,您需要传递一个 :id。这样,在您的 Controller 中,您将能够通过给定的 :id => Goal.find(params[:id]) 找到记录。因此,在您的测试中,您需要传递此 :id,类似于:

get :edit, id: 1 # mapping to /goals/1/edit

如果您手动添加此路由 get 'goals/edit',它会起作用,因为它直接映射到 /goals/edit(注意没有 : id).

顺便说一句,我建议您查看官方路由指南:http://guides.rubyonrails.org/routing.html

关于ruby-on-rails - ActionController::UrlGenerationError:尝试测试 Controller 时没有路由匹配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33377396/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com