简体   繁体   中英

ActionController::UrlGenerationError: No route matches when trying to test the controller

I'm getting an ActionController::UrlGenerationError: No route matches (:action => "edit", :controller => "goals") error, when I'm trying to test the goals controller

Here is my 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

This is my 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

My 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

I find it weird that if I use get 'goals/edit' instead of resources :goals the test passes.

Thank you very much for any guideline.

When you use resources :goals Rails generates for you the following routes (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

As you can see, to hit the edit action /goals/:id/edit you need to pass an :id . That way, in your controller you'll be able to find the record by the given :id => Goal.find(params[:id]) . So, in your tests you need to pass this :id , something like:

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

If you manually add this route get 'goals/edit' , it works because it maps directly to /goals/edit (NOTE there is no :id ).

Btw, I recommend you to review the official Routing guides: http://guides.rubyonrails.org/routing.html

@goal = Goal.create(your params here) or use factory girl gem or fixtures

you should pass id get :edit ,id: @goal

useful article

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM