RSpec 0.9.x の変更点私的メモ
- 最近は主に 0.8.x を使っていた
- 変ったよ〜という話は聞きつつもとりあえず 0.8.x で不便を感じていなかったので(互換性あるし)で流してた
- Rails勉強会@東京のWikiでYuguiさんが「変わりすぎwwww」
- どれどれ、と見てみて噴いた ← いまここ
サンプル from 本家
describe Account, " when first created" do before do @account = Account.new end # (1) it "should have a balance of $0" do @account.balance.should eql(Money.new(0, :dollars)) end after do @account = nil end end
(1) describe - it と context - specify
いままでは context - specify で書いていたところが describe と it で書けるようになってます。従来のももちろんOK。
ちょっと触った感じでは機能面での違いはなさそうなんですが。。声に出して読んでみると味わいがあります。
また、shouldに関しては 0.8.x スタイルを従来どおり使えそうなので問題ないかと
(2) setup - teardown と before - after
setup - teardown の書き方にも新しいものができました。これまた、従来のものも使えます。
0.8.x | 0.9.x で追加 | ||
context_setup | before(:all) | ||
setup | before | ||
teardown | after | ||
context_teardown | after(:all) |
setup系とbefore-after系の両方を記述した場合の実行順は、法則性はあるものの複雑な感じです。定義順に関係がある模様。
要するに、前処理と後処理それぞれで定義した順番に実行されるみたいですね。う〜ん。混乱を避けるためにも混在させないほうがベネ。
Shared-behaviors
これはよさそう。サンプル
describe "All Employees", :shared => true do it "should be payable" do @employee.should respond_to(:calculate_pay) end end describe "All Managers", :shared => true do it_should_behave_like "All Employees" it "should be bonusable" do @employee.should respond_to(:apply_bonus) end end describe Officer do before(:each) do @employee = Officer.new new it_should_behave_like "All Managers" it "should be optionable" do @employee.should respond_to(:grant_options) end end
要は複数のコンテキスト/クラス/インスタンスで共通する仕様がある場合、それをまとめて書けるってことですかね。
最近はeachで回して複数のコンテキストを動的に定義する、という書き方をしていたんですが、それをもっと宣言的に書けるようになってるってことのようです。
0.9.xの私的ツボです。
Rails プラグイン回り
地味ですが、いろいろ便利になっています。ただし、新機能ではなく私が知らなかっただけかもしれないので注意。
Model のバリデーション結果のspec
model.should have(:no).errors_on(:attribute) model.should have(1).error_on(:attribute) model.should have(3).errors_on(:attribute)
Controllerのspec
これは面白い。
http://rspec.rubyforge.org/documentation/rails/writing/controllers.html
うれしいのは、renderのspecがリクエストの後に書けるようになっていること。これまでは
context do .. setup do # このようにリクエスト前に書くか controller.should_render :template => path get "list" end specify do # このhaveは現在完了形のアレ wwww controller.should_have_rendered :template => path end end
だったのが、下のように普通に書けるみたいです。そういえば、ここが原因で勉強会ではまったこともありました。
describe SampleController do before do get 'index' end it "the response should render 'list'" do response.should render_template(:list) end end
ビューに関しては従来から大きな変更はなさそうです。現状でも結構満足しているのでOK。should have_tag() (assert_select) はやっぱり素敵だ。
とりあえずざっと見た感じではこんなところですかね。気づいたら適宜追加します。