In this second part of a four-part series on how to add tagging support to an ecommerce website using Ruby on Rails, you'll learn what modifications you need to make so that items in your system can be tagged without breaking things. This article is excerpted from chapter seven of the book Practical Rails Projects, written by Eldon Alameda (Apress; ISBN: 1590597818).
Preparing to Add Tagging Support - Unit Testing the Model (Page 2 of 3 )
Upgrading the acts_as_taggable gem or changing your own code can easily break the tagging functionality. To prevent this, or at least minimize the risk of this happening in our production environment, we’ll create unit tests for the model. These tests will be used to verify that we can add tags to a book and find the book.
Opentest/unit/book_test.rbin your editor and add the followingtest_taggingmethod:
The unit test first loads a single book from thebooksfixture and assigns the tagsElvisandThrillerto it. Then the test reloads the book from the database and verifies that the book has been tagged correctly. The verification is done by using theacts_as_taggableAPI methodstagged_withandfind_tagged_with.
Tip You can usebook.errors.full_messages.join(';')to get a string representation of all validation errors after an unsuccessful save of an ActiveRecord object. This is useful when debugging validations.
Next, run the unit test, and you should see all tests pass:
$ ruby test/unit/book_test.rb
-------------------------------------------- Loaded suite test/unit/book_test Started ..... Finished in 0.159311 seconds.