2014-05-15 48 views
1

我想測試我的控制器。一切都很好,直到我試圖測試update行動。如何在使用minitest的Rails中測試控制器的更新方法?

這是我的測試

require 'test_helper' 

class BooksControllerTest < ActionController::TestCase 
    test "should not update a book without any parameter" do 
     assert_raises ActionController::ParameterMissing do 
      put :update, nil, session_dummy 
     end 
    end 
end 

這是我的控制器

class BooksController < ApplicationController 

    (...) 

    def update 
     params = book_params 
     @book = Book.find(params[:id]) 

     if @book.update(params) 
      redirect_to @book 
     else 
      render 'edit' 
     end 
    end 

    (...) 

    def book_params 
     params.require(:book).permit(:url, :title, :price_initial, :price_current, :isbn, :bought, :read, :author, :user_id) 
    end 
end 

我的應用程序的書籍控制器路線如下:

books GET /books(.:format)      books#index 
      POST /books(.:format)      books#create 
new_book GET /books/new(.:format)     books#new 
edit_book GET /books/:id/edit(.:format)    books#edit 
    book GET /books/:id(.:format)     books#show 
      PATCH /books/:id(.:format)     books#update 
      PUT /books/:id(.:format)     books#update 
      DELETE /books/:id(.:format)     books#destroy 

當我運行rake test我得到:

1) Failure: 
BooksControllerTest#test_should_not_update_a_book_without_any_parameter [/Users/acavalca/Sites/book-list/test/controllers/books_controller_test.rb:69]: 
[ActionController::ParameterMissing] exception expected, not 
Class: <ActionController::UrlGenerationError> 
Message: <"No route matches {:action=>\"update\", :controller=>\"books\"}"> 
---Backtrace--- 
test/controllers/books_controller_test.rb:70:in `block (2 levels) in <class:BooksControllerTest>' 
test/controllers/books_controller_test.rb:69:in `block in <class:BooksControllerTest>' 
--------------- 

那麼,我在這裏錯過了什麼?我已經完成了搜索,但找不到任何東西。只有幾個RSpec的例子,看起來和我所做的很相似,但我還是沒有任何線索。

回答

4

您需要至少發送一個Book的ID。請注意,路線是這樣的:

PUT /books/:id(.:format)     books#update 

:id部分是URL的一個組成部分。這意味着試圖執行PUT/books/沒有任何意義,但是執行/books/1是一個有效的URL,即使ID 1與數據庫中的任何記錄都不匹配。

您必須至少發送:id的參數才能進行此測試。

+0

呃!它的工作,謝謝! :) –

+0

沒問題!一定要將這個回答標記爲答案! – MrDanA

相關問題