Unit testing lets you work with your data on a pretty atomic level—checking validations, data storage, and similarly tightly focused issues. Rails scaffolding gives you only a very simple placeholder file, shown in Example 12-7. That file is definitely not sufficient for any real testing, and you should add unit tests that test validations for each field in your model.
Unit testing, in Rails’ unique way of performing it, is only about testing models. If you have previous experience with testing in other environments, this can be confusing. If Rails is your first testing experience, don’t worry about it, but remember that unit testing in Rails is different from unit testing elsewhere.
Example 12-7. The mostly useless generated unit test file, test/unit/award_test.rb
require 'test_helper' class AwardTest < ActiveSupport::TestCase # Replace this with your real tests. def test_truth assert true end end
Example 12-7 does show one feature of
statement, which expects its argument to return
true and reports a test failure if it doesn’t. (You can also use
deny to report failure on
Unit tests are pretty straightforward to write, though are rarely exciting code. In general, they should reflect the validations performed by the model. Example 12-8 shows a definition for the award model that highlights some easily tested constraints.
Example 12-8. An award model with constraints defined
class Award < ActiveRecord::Base # every award is linked to a student, ...