1. Technology
You can opt-out at any time. Please refer to our privacy policy for contact information.

Writing a Unit Test


Writing a Unit Test in Rails

Good, we can run tests with a single rake task. On to writing a test so we can implement something in our application. So, we want to validate the presence of the body. We'll write a simple test for that in the post_test.rb file. The test simply tries to create a Post object and save it without assigning a title. The assert assertion will fail if its first argument is false or nil. Since we want the opposite of this (to fail if it's true, or if it was saved successfully without a title), we'll simply use the ! operator.

require 'test_helper'

class PostTest < ActiveSupport::TestCase
# Replace this with your real tests.
test "the truth" do
assert true

test "must have a body" do
p = Post.new
assert !p.save, "Post was saved without a body"
  1. About.com
  2. Technology
  3. Ruby
  4. Ruby on Rails
  5. Test-Driven Rails
  6. Writing a Unit Test

©2014 About.com. All rights reserved.