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

Are Your Models Working Correctly?


Unit Tests in Rails

Since you'll start your app by drawing up some models, you should start by writing some unit tests. When talking about Rails, unit tests test your models. Other models, such as integration and functional tests, will test your controllers and views.

All of your tests reside in the test directory, while the unit tests reside in the test/unit directory. Exploring this directory, you'll find it empty at first. This directory will either be manually populated by you or, more likely, populated by the scaffold generator. Since using generators to do the grunt work is preferred, generating your tests along with your models is a good idea.

If you go ahead and scaffold your first model, you can explore what it will create in the test/unit folder. In this example, I'll make a little microblog app. It won't have users, just posts. The posts are really simple, they just have the normal timestamps created_at and modified_at and a body. I'll start by running the scaffold generator and migrating the database.

$ script/generate scaffold post body:text
exists app/models/
exists app/controllers/
exists app/helpers/
create app/views/posts
exists app/views/layouts/
exists test/functional/
exists test/unit/
exists public/stylesheets/
create app/views/posts/index.html.erb
create app/views/posts/show.html.erb
create app/views/posts/new.html.erb
create app/views/posts/edit.html.erb
create app/views/layouts/posts.html.erb
create public/stylesheets/scaffold.css
create app/controllers/posts_controller.rb
create test/functional/posts_controller_test.rb
create app/helpers/posts_helper.rb
route map.resources :posts
dependency model
exists app/models/
exists test/unit/
exists test/fixtures/
create app/models/post.rb
create test/unit/post_test.rb
create test/fixtures/posts.yml
create db/migrate
create db/migrate/20090126123517_create_posts.rb
$ rake db:create:all
$ rake db:migrate
== CreatePosts: migrating ====================================================
-- create_table(:posts)
-> 0.0193s
== CreatePosts: migrated (0.0198s) ===========================================
  1. About.com
  2. Technology
  3. Ruby
  4. Ruby on Rails
  5. Test-Driven Rails
  6. Test Driven Development in Ruby--Unit Tests in TDD with Rails

©2014 About.com. All rights reserved.