In this conclusion to a four-part series on building an online bookstore application in Ruby-on-Rails, you'll learn how to edit and delete authors, and more. This article is excerpted from chapter two of the book Practical Rails Projects, written by Eldon Alameda (Apress; ISBN: 1590597818).
Managing Authors in an Online Bookstore - Deleting an Author (Page 3 of 4 )
For the Delete Author user story, we simply want to test that posting a form to the destroyaction correctly deletes the author from the database and then redirects us to theindexpage. Letís openauthor_controller_test.rbagain and add another test case to it.
def test_destroy assert_difference(Author, :count, -1) do post :destroy, :id => 1 assert_response :redirect assert_redirected_to :action => 'index' end end
The test code is fairly simple, and the only thing new is that this time we pass-1as thedifferenceargument toassert_difference, in order to make sure the number of authors decreases by one as the result of thedestroy action.
Implementing thedestroyaction is straightforward. We donít need a view for it, since the action just deletes the author and redirects back to the author list.
Thatís all the code it takes to delete an author. We again fetch the right author from the database using thefindmethod, and then use the ActiveRecorddestroymethod to delete the author from the database. In between, we populate the flash notice so that theindexpage where we redirect the user will show a notification to the user about the successful deletion.
The result is 31 assertions, no failures, no errors. It works! It works!!! We exchange a couple of high-fives before we start the WEBrick server again, and point the browser tohttp://localhost:3000/admin/author/. The result is shown in Figure 2-4.