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 (Page 1 of 4 )
Viewing an Author
As you might have noticed, creating the Author model also created a file calledauthors.ymlintest/fixtures. This is called a fixture file. Fixtures are mock data that can be used to populate the database with consistent data before each test method. Since the test database is purged before every test method, you know that all the data that exists in the database at that point came from the fixture files.
It would be handy to have a few authors in the database for testing our view functionality, so we go ahead and create a couple of author fixtures inauthors.yml:
joel_spolsky: id: 1 first_name: Joel last_name: Spolsky jeremy_keith: id: 2 first_name: Jeremy last_name: Keith
Putting the linefixtures :authorsin the beginning of our functional test class makes Rails load the author fixtures automatically before every test method inside that class:
class Admin::AuthorControllerTest < Test::Unit::TestCase fixtures :authors ... end
Now we can rest assured that when we start testing viewing an author, we have two items in ourauthors table.
We’ll keep the show author page very simple. We just want to make sure that we’re fed the right template and that the author is the one we’re expecting. Add the following test case to the bottom ofauthor_controller_test.rb:
def test_show get :show, :id => 1 assert_template 'admin/author/show' assert_equal 'Joel', assigns(:author).first_name assert_equal 'Spolsky', assigns(:author).last_name end
Here, we simply request the show page for one of our fixture authors and check that we get the correct template. Then we use theassigns helper to check that the author instance variable assigned in the action is the one it should be.assignsis a test helper method that can be used to access all the instance variables set in the last requested action. Here, we expect that theshowaction assigns a variable@authorand that the variable responds to the methodsfirst_nameandlast_name, returning “Joel” and “Spolsky,” respectively.
The controller code for theshowaction is simple. We fetch the author from the database and set the page title to the author’s name.
def show @author = Author.find(params[:id]) @page_title = @author.name end
Now let’s open the view file,app/views/admin/author/show.rhtml, and add the template code: