Railsでテストを書いてみる(Rspec編)
rspec 環境設定
Rails3.0.3に rspecをインストールするのに少しハマったのでメモ
- gem のアップデート
$ sudo gem update --system $ gem -v 1.5.2
- activesupport のアップグレード
$ sudo gem update activesupport $ gem list | grep active activemodel (3.0.4, 3.0.3) activerecord (3.0.3, 2.3.5, 2.2.2, 1.15.6) activeresource (3.0.3, 2.3.5, 2.2.2) activesupport (3.0.4, 3.0.3, 2.3.5, 2.2.2, 1.4.4)
$ sudo gem install rspec $ sudo gem install rspec-rails $ gem list | grep rspec rspec (2.5.0) rspec-core (2.5.1) rspec-expectations (2.5.0) rspec-mocks (2.5.0) rspec-rails (2.5.0)
- hoe のインストール
- 何に使うかよくわかってないけど必要との記事をどこかで見かけた。
$ sudo gem install hoe $ gem list | grep hoe hoe (2.9.1)
- bundler のアップデート
- bundle install を実行したらエラーになったのでアップデートする
$ sudo gem update bundler $ gem list | grep bundle bundler (1.0.10, 1.0.7)
- rspec を generate したらエラーが。Gemfile を変更しないといけないらしい
$ rails g rspec:install
Could not find generator rspec:install.
source 'http://rubygems.org' gem 'rails', '3.0.3' gem 'mysql2' group :development do gem 'rspec-rails', '2.5.0' end group :test do gem 'rspec', '2.5.0' end
$ rails g rspec:install create .rspec create spec create spec/spec_helper.rb
行けた!
- モデルに対する spec を生成
$ rails g rspec:model tune create spec/models/tune_spec.rb
- spec の実行
$ rake spec (in /Users/hoge/rails_work/practice) /System/Library/Frameworks/Ruby.framework/Versions/1.8/usr/bin/ruby -S bundle exec rspec ./spec/models/tune_spec.rb * Pending: Tune add some examples to (or delete) /Users/hoge/rails_work/practice/spec/models/tune_spec.rb # Not Yet Implemented # ./spec/models/tune_spec.rb:4 Finished in 0.00024 seconds 1 example, 0 failures, 1 pending
とりあえず空テストの実行まで完了!
テストコードの記述
- fixture を入れるには spec/fixtures に yml データを作成する
$ vi spec/fixtures/tunes.yml
one: name: splash album: Dramatic tuning: DADGAD progress: 100 # column: value # two: name: 翼 album: Be Happy tuning: DADGAD progress: 100
- spec ファイルには fixtures :tunes を書くとテストデータが挿入される
$ vi spec/models/tune_spec.rb
require 'spec_helper' describe Tune do fixtures :tunes describe "DBにあらかじめデータが登録されている場合" do it "DB内のデータを全て読み出せる" do tune = Tune.find(:all) tune.length.should == 2 end end describe "新たに曲データを追加した場合" do before do tune = Tune.new tune.name = "sun dance" tune.album = "Dramatic" tune.tuning = "EAEF#BE" tune.progress = 100 tune.save end it "データ数が増加している" do tune = Tune.find(:all) tune.length.should == 3 end it "追加したデータを読み出せる" do tune = Tune.find(:all, :conditions=>[ "name=?", 'sun dance']) tune[0].name.should == "sun dance" end end end
- model のテストは何を書いたらいいのかわからない。上だと、ActiveRecordのテストをしているような感覚になる。