Chloe
Chloe

Reputation: 26264

Why does my Rails controller test not route?

Why doesn't my test case work and why does it complain about a route not found? It works in the browser.

Code

class UsersController < ApplicationController
  def deposit

Routes

resources :users do
  post 'deposit', to: :deposit

Test Case

class UsersControllerTest < ActionController::TestCase
  test "deposit" do
    post :deposit, {id: 1} 

Log

UsersControllerTest#test_deposit: ActionController::UrlGenerationError: No route matches {:id=>"1", :controller=>"users", :action=>"deposit"}

Version

Rails 4.0.0

Realated

I saw this, but it did not help when I used '1'. Rails routes issue with controller testing

I saw this, but I already added :id and it still won't work. Testing Rails 4 Controller

Upvotes: 1

Views: 293

Answers (2)

Billy Chan
Billy Chan

Reputation: 24815

The reason is your route definition is not so standard.

A better way to add RESTful actions is to use member

resources :users do
  member do
    post 'deposit'
  end
end

Or

resources :users do
  post 'deposit', on: :member
end

And here is the reason why you can only use user_id but not id

You can leave out the :on option, this will create the same member route except that the resource id value will be available in params[:photo_id] instead of params[:id]. http://guides.rubyonrails.org/routing.html#adding-more-restful-actions

Upvotes: 3

Chloe
Chloe

Reputation: 26264

Odd,

{user_id: 1}

worked. This is one rake route:

user_deposit POST /users/:user_id/deposit(.:format)

While this is another:

edit_user GET /users/:id/edit(.:format)

Upvotes: 0

Related Questions