In this second part of a four-part series on setting up a forum in Ruby on Rails, you'll learn how to unit test a model, generate a forum controller and view, and more. This article is excerpted from chapter six of the book Practical Rails Projects, written by Eldon Alameda (Apress; ISBN: 1590597818).
Basic Tests for Forum Implementation (Page 1 of 4 )
Unit Testing the Model
It is a good idea to have proper unit tests in place, even if you're using an external plugin that has been tested thoroughly. The plugin API might change in later releases, and this would probably go unnoticed until one of your customers informs you about the problem.
We'll create a basic test that verifies that you can create a post and also create a reply to it. Remember that the generate script has already created an empty unit test for us. All we need to do is add the code shown in Listing 6-2 to test/unit/forum_post_test.rb .
assert post.root? assert_equal 1, post.all_children().size assert_equal reply, post.all_children() end end
Notice that the test uses the authors fixture that we created in Chapter 2. First, the unit test creates a new post, which is the root post of a new thread. Then it saves the post and verifies that it was successfully saved to the database with an assert . Recall that the save method returns false if the object was not saved successfully. We double-check that the post can be found with the find_by_name dynamic finder method (introduced in Chapter 3). The unit test also verifies that the first post is the root post by calling root? . This method returns true if the post has no parent posts.
We also want to be sure that someone can reply to the post, which is why we create a reply to the root post. This is done by creating a new post and setting the parent_id column to the id of the root post. After saving the reply post, we verify that the post really is a reply to the first post by calling the child? method. This method returns true if the post is a child, or reply, of another post.
At the end of the unit test, we verify that the root post has exactly one child post, and that the first post returned by all_children returns the reply.
Before running the tests, clone the development database structure to the test database by executing the following command:
Next, run the unit test as follows:
$ ruby test/unit/forum_post_test.rb
-------------------------------------------- Loaded suite test/unit/forum_post_test Started . Finished in 0.101902 seconds.