RSpec-RailsでスタブにRRを使ってみた
RSpecはもともとスタブやモックをサポートしているんだけど、他のライブラリのスタブを組み込むこともできる。
機能的にはどのライブラリでも大差は無いんだと思うんだけど、RSpecのスタブとモックは何となく好きになれない。*1
というわけでスタブにRRを使ってみた。
RRのインストール
gemで一発
sudo gem install RR
RSpecのスタブライブラリにRRを使う宣言
/path/to/project/spec/spec_helper.rbで以下を追加
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 #←を追加
restful-authenticationのスタブを書き換えてみる
今restful-authenticationを使っているので、
restful-authenticationがデフォルトで生成する*2user_loginメソッド中のスタブをRRで書き換えてみる
#RSpecのスタブを使ったuser_loginメソッド #restful-authenticationが自動で生成する def user_login session[:user_name] = 'test' session[:prepared] = true u = stub_model(User) u.stub!(:login).and_return('test') u.stub!(:active?).and_return(true) u.stub!(:name).and_return('ユーザ') u.stub!(:crypted_password).and_return('123456789') if defined? controller controller.stub!(:current_user).and_return(u) else # helperでも使えるように stub!(:current_user).and_return(u) end u end
#たぶんこんな感じ def user_login session[:user_name] = 'test' session[:prepared] = true stub(User).active?{true} stub(User).login{'test'} stub(User).name{'ユーザ'} stub(User).crypted_password{'123456789'} if defined? controller stub(controller).current_user{User} else stub.current_user{User} end return User end
一応テストは通ったからほぼ同じように書き換えれたと思う。