Skip to Main Content
Learning Rails
book

Learning Rails

by Simon St. Laurent, Edd Dumbill
November 2008
Beginner content levelBeginner
448 pages
12h 25m
English
O'Reilly Media, Inc.
Content preview from Learning Rails

Unit Testing

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.

Note

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 testing—the assert 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 true.)

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, ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Learning Rails 5

Learning Rails 5

J. Mark Locklear, Eric J Gruber, Barnabas Bulpett
Mastering Ruby Closures

Mastering Ruby Closures

Benjamin Tan Wei Hao
Ruby on Rails® Bible

Ruby on Rails® Bible

Timothy Fisher

Publisher Resources

ISBN: 9780596154943Supplemental ContentErrata