Unit tests in Ruby on Rails
How to write and run your first unit test for your ruby on rails webapp
Fist time setup
$ rake db:test:load
|rake db:test:clone||Recreate the test database from the current environment’s database schema|
|rake db:test:clone_structure||Recreate the test database from the development structure|
|rake db:test:load||Recreate the test database from the current schema.rb|
|rake db:test:prepare||Check for pending migrations and load the test schema|
|rake db:test:purge||Empty the test database.|
Writing a test
Running your tests
ruby -Itest test/unit/recette_test.rb
|rake test||Runs all unit, functional and integration tests. You can also simply run rake as the test target is the default.|
|rake test:benchmark||Benchmark the performance tests|
|rake test:functionals||Runs all the functional tests from test/functional|
|rake test:integration||Runs all the integration tests from test/integration|
|rake test:plugins||Run all the plugin tests from vendor/plugins/*/**/test (or specify with PLUGIN=_name_)|
|rake test:profile||Profile the performance tests|
|rake test:recent||Tests recent changes|
|rake test:uncommitted||Runs all the tests which are uncommitted. Supports Subversion and Git|
|rake test:units||Runs all the unit tests from test/unit|
If you are on an large existing project and are just starting writing your tests you may face a couple of walking on broken glass debugging.
Problem: DELETE FROM non-existing tables
ActiveRecord::StatementInvalid: SQLite3::SQLException: no such table: friends: DELETE FROM "friends"
Let's check the log test.log
[1m[36mFixture Delete (0.0ms)[0m [1mDELETE FROM "friendrequests"[0m
[1m[35mFixture Delete (0.0ms)[0m DELETE FROM "friends"
SQLite3::SQLException: no such table: friends: DELETE FROM "friends"
The solution is surprisingly to remove a file from the test/fixture folder
Problem: INSERT INTO a table that has no column named 'XYZ'
This is due to your fixture deriving from your models schema. The solution is to fix your fixtures files.
In my case the solution was to change this for that :
Version used for this article
Ruby 2.1.9p490 (2016-03-30 revision 54437)
Further suggested reading