Railsでテストを書いてみる(UnitTest編)
前準備の環境構築
改めておさらいしつつ。Rails3.0.3
- mysql でアプリを生成
$ rails new practice -d mysql
- DB生成
$ cd practice
$ rake db:create:all
- DB確認
$ mysql5 -u root -p mysql> show databases; +----------------------+ | Database | +----------------------+ | information_schema | | mysql | | practice_development | | practice_production | | practice_test | | sandbox | | test | +----------------------+ 7 rows in set (0.00 sec)
-
- practice_XXXX が3つ出来てればOK
- モデルを生成
$ rails generate model tune invoke active_record create db/migrate/20110216080756_create_tunes.rb create app/models/tune.rb invoke test_unit create test/unit/tune_test.rb create test/fixtures/tunes.yml
- モデルにカラムを追加
$ vi db/migrate/20110216080756_create_tunes.rb
class CreateTunes < ActiveRecord::Migration def self.up create_table :tunes do |t| t.string :name #add t.string :album #add t.string :tuning #add t.integer :progress #add t.timestamps end end def self.down drop_table :tunes end end
- テスト実行
$ rake test (in /Users/hoge/rails_work/practice) Loaded suite /Library/Ruby/Gems/1.8/gems/rake-0.8.7/lib/rake/rake_test_loader Started . Finished in 0.034337 seconds. 1 tests, 1 assertions, 0 failures, 0 errors
とりあえずモデルのテスト環境は揃った。
テストデータの挿入
- yml ファイルにテストデータを設定できる。
- 試しに2つ適当に入れてみる
$ vi test/fixtures/tunes.yml
one: name: splash album: Dramatic tuning: DADGAD progress: 100 two: name: 翼 album: Be Happy tuning: DADGAD progress: 10
テストコードの記述
- さっき設定したテストデータの数と、テストデータの内容を見てみる
$ vi test/unit/tune_test.rb
require 'test_helper' class TuneTest < ActiveSupport::TestCase # テストデータの数を判定 test "test_datas_len_is_2" do tune = Tune.find(:all) assert_equal 2 ,tune.length end # 固有のテストデータの存在を判定 test "test_datas_splash_tuning_is_DADGAD" do tune = Tune.find(:all,:conditions=>["name=?","splash"])[0] assert_equal "DADGAD" ,tune.tuning end end