Writing Unit Tests in Ruby on Rails

Rails Framework is not capable of generating unit tests for you but it is capable of setting up framework for unit testing and functional testing that you can use as a starting point to the creation of test cases suite.

Unit Tests created by the Rails Framework run against test database and as such they require to have test database to be in place for unit test execution.

Rails generate command creates not only model and controller but unit test script as well. In addition to unit tests, it creates a fixture for unit tests with test data stored in YAML file to be later loaded into mydb_test database.

> rails generate model Item

This line of code generates two test files that you will be able to use for putting together unit test suite. These files are stored under /test/ folder:

/test/models/item_test.rb
/test/fixtures/items.yml

Another line of Rails command code will generate a controller as well as test script for this controller.

> rails generate controller items list

Two more files are created after you line the above line of code. These files are placed under /test/ folder as well.

/test/controllers/items_conteroller_test.rb
/test/helpers/items_helper_test.rb

These two files are used to write tests for your controller. You will write you test first as mandated by the test driven development.

In order to run test cases in your project, you need to invoke rake command line. This command line not only starts up your test case, but also provision model into test database and populates with test data as defined inside YAML file.

Here is a simple example of test case written to test ActiveRecord and Rails application

class ItemTest < ActiveSupport::TestCase
  test “my test” do
   assert_kind_of Item, items(:one)
  assert_not_equal items(:one), items(:two)
 end
end

Rails assert method are: assert_dom_equal, assert_dom_not_equal, assert_generates, assert_no_tag, assert_recognize, assert_redirect_to, assert_response, assert_routing, assert_tag, assert_template, assert_valid.

Featured pages

Ruby

Set of Ruby Object Oriented Programming Language tutorials that cover such topics as Ruby strings, …

Rails

Rails Framework tutorial teaches you how to utilize de facto framework of choice for Ruby developme…

Ruby Duck Typing

“If an object quacks like a duck just go ahead and treat it as a duck” – this fun…

Regular Expressions

Ruby uses the =~ operator to check any given string against regular expression. For example, a stri…

Credit Card Number

Every last digit of any credit card is a check sum digit that is determined by all digits in front …

Ruby Arrays

Ruby Programming Language has built in support for Arrays. Arrays help you define some of the compl…

Ruby Hashes

Hashes are very similar to arrays in Ruby and hashes interface is similar to Ruby array interface. …

Ruby Code Block

Ruby is very unique language when it comes to code blocks. You can simply pass a code block to a me…