8. Testing Your Models

8.1. A Unit Test

Unit tests are what we use to test our models. Generally, there is one test for each model. The test stubs are created automatically when you use script/generate model SecretAgent (for example).

Let's take a look at what a unit test might look like.

# hook into the Rails environment
require File.dirname(__FILE__) + '/../test_helper'

class SecretAgent < ActiveSupport::TestCase
  fixtures :secret_agents

  # ensure the SecretAgent plays well with the database
  def test_create_read_update_delete
    # create a brand new secret agent
    jimmy = SecretAgent.new("jagent", "unbelievablysecretpassword")

    # save him
    assert jimmy.save

    # read him back
    agent = SecretAgent.find(jimmy.id)

    # compare the usernames
    assert_equal jimmy.username, agent.username

    # change the password by using hi-tech encryption
    agent.username = agent.username.reverse

    # save the changes
    assert agent.save

    # the agent gets killed
    assert agent.destroy
  end
end

In this basic unit test, we're exercising the SecretAgent model. In our solitary test, we're proving a bunch of things about our SecretAgent model. We try 4 different assertions to test that we can do the basics with the database such as create, read, update and delete (creatively known as CRUD).

It is up to you to decide just how much you want to test of your model. Ideally you test anything that could possibly break, however, it is really trial and error. Only you know what's best to test.

You most certainly want to test the validation code, and additionally, you probably want a least 1 test for every method in your model.