繁体   English   中英

如何使用minitest在Rails中测试控制器的更新方法?

[英]How to test a controller's update method in Rails using minitest?

我正在尝试测试我的控制器。 一切正常,直到我尝试测试update操作为止。

这是我的测试

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控制器的路由如下:

    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示例,看起来与我所做的非常相似,但我仍然不知道。

您至少需要向其发送一Book的ID。 请注意,路线如下所示:

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

:id部分是URL的组成部分。 这意味着尝试对/books/进行PUT没有任何意义,但是对/books/1进行PUT是有效的URL,即使ID 1与数据库中的任何记录都不匹配也是如此。

您至少必须为:id发送参数才能使此测试正常进行。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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