In this conclusion to a three-part series on building an online book catalog application with Ruby-on-Rails, we'll finish creating the search ability and add both a regular page and an RSS feed that lets users see the latest book titles to arrive at the store. This article is excerpted from chapter four of the book Practical Rails Projects, written by Eldon Alameda (Apress; ISBN: 1590597818).
Adding an RSS Feed to an Online Book Catalog - Implementing the Get Latest Books User Story (Page 2 of 3 )
So far, we have created a book catalog that lets Jill browse and search books, and see their details. The last part of the sprint is to implement the ultimate desire of a book-lover: a list of the latest books. We’ll implement this feature both as a normal web page and as an RSS feed, so that Jill can skip the step of using a browser altogether. Again, we’ll start by writing a test for the latest books page.
Updating the Integration Test
Add another method to theBrowsingTestDSLmodule intest/integration/browsing_and_searching_test.rb:
def views_latest_books get "/catalog/latest" assert_response :success assert_template "catalog/latest"
You can see that the method is similar tobrowse_indexandgo_to_second_page, but it has a different URL and desired template. The only thing special here is that we iterate over theBookobjects returned byBook.latestand check that there is adt element for each book. To make this work, we first need to create alatestclass method for ourBookclass. Add the following method toapp/models/book.rb:
We could have used thefindmethod as such in our test. However, we’re going to need the exact same code later, so it’s a good idea to wrap it inside a class method. We also need to add a call to our new method in the actual test case:
def test_browsing_the_site jill = enter_site(:jill) jill.browse_index jill.go_to_second_page jill.get_book_details_for "Pride and Prejudice" jill.searches_for_tolstoy jill.views_latest_books end
Now that we have a (failing, but you guessed that) test in place, the next thing to do is to update the controller.
Modifying the Controller
Openapp/controllers/catalog_controller.rband fill thelatestaction with content:
def latest @page_title = "Latest Books" @books = Book.latest end
There’s nothing special in there. We just set the page title and then use theBook.latestclass method we just created to fetch the ten latest books.
Modifying the View
The view file,app/views/catalog/latest.rhtml, is even simpler:
<%= render :partial => "books" %>
We can fire our test case and see that everything works oh so smoothly.