RailsのテストにRSpec(RSpec-Rails)&RR(rspec-rr)を使う方法まとめ

ここ数日でRailsのテスティングフレームワークRSpecを使用して、
さらにモック、スタブのライブラリにRRを使えるようにしたのでその方法をまとめておきます。
それぞれのバージョンは以下の通り

Rails
2.2.2
Rspec
1.1.12
RR
0.7.1
rspec-rr
gem未収録、github http://github.com/mdub/rspec-rr/tree/master

Railsのインストール

gemでRailsをインストールする。

sudo gem install rails

RSpecRSpecRailsのインストール

gemでRSpecRSpec-Railsをインストールする。

sudo gem install rspec
sudo gem install rspec-rails

RRのインストール

gemでRRをインストールする。

sudo gem install rr

Railsプロジェクトの作成

Railsのプロジェクト「test」を作成する。

cd /path/to/project/ #←プロジェクトを作成するフォルダに移動
rails test           #←プロジェクト名がtestの場合

RSpec-RailsRailsプロジェクトに組み込む

RSpecRSpec-RailsRailsで使えるようにする。

ruby script/generate rspec

ちなみに上記の設定で以下のコマンドが使えるようになる

ruby script/generate rspec_model hoge #作成するリソースがhogeの場合
ruby script/genarate rspec_controller hoge
ruby script/genarate rspec_scaffold hoge

上記コマンドを発行するとapp配下のファイルと一緒にspec配下のファイルも作ってくれる

RRをRSpecに組み込む

/path/to/project/spec/spec-helper.rbを編集して「config.mock_with :rr」を追加

ENV["RAILS_ENV"] = "test"
require File.expand_path(File.dirname(__FILE__) + "/../config/environment")
require 'spec'
require 'spec/rails'

Spec::Runner.configure do |config|
  # If you're not using ActiveRecord you should remove these
  # lines, delete config/database.yml and disable :active_record
  # in your config/boot.rb
  config.use_transactional_fixtures = true
  config.use_instantiated_fixtures  = false
  config.fixture_path = RAILS_ROOT + '/spec/fixtures/'

  config.mock_with :rr      #←を追加

rspec-rrのインストール

rspec-rrはRSpec-RailsのRR版です。
RSpec-Railsでお馴染みのmock-modelとかのメソッドがRRで使えるようになります。
オリジナルはjosephwilkさんがgithubで公開してくれているんですが、
これを組み込むとstub-modelsというメソッドでエラーがでちゃったんでforkして修正版を公開してくれているmdubさんのrspec-rrを使います。

ruby script/plugin install git://github.com/mdub/rspec-rr.git

rspec-rrを組み込む

/path/to/project/spec/spec-helper.rbを編集して「require 'spec/rr'」を追加

ENV["RAILS_ENV"] = "test"
require File.expand_path(File.dirname(__FILE__) + "/../config/environment")
require 'spec'
require 'spec/rails'
require 'spec/rr'      #←を追加

Spec::Runner.configure do |config|
  # If you're not using ActiveRecord you should remove these
  # lines, delete config/database.yml and disable :active_record
  # in your config/boot.rb
  config.use_transactional_fixtures = true
  config.use_instantiated_fixtures  = false
  config.fixture_path = RAILS_ROOT + '/spec/fixtures/'

  config.mock_with :rr

これで以下のコマンドが使えるようになります。

ruby script/genarate rspec_rr_scaffold

上記コマンドで作られるspecファイルは、rspec_scaffoldで作られるspecのモックとスタブ部分がRSpecからRRに変更されたものです。
RRの勉強にもなるのでとても便利!
josephwilkさん++
mdubさん++