# Array spec
describe Array, "[1,2,3]" do
subject { [1,2,3] }
it {should be_an_instance_of(Array)}
its(:size) {should == 3}
it "should respond to :sort" do
should respond_to(:sort)
end
end
例外捕捉だってこんなにスマート
require "timeout"
describe Timeout, "timeout" do
it "should raise TimeoutError if time is over" do
lambda {
Timeout.timeout(0.1) {sleep 0.2}
}.should raise_error(TimeoutError)
end
it "should not raise TimeoutError unless time is over" do
lambda {
Timeout.timeout(0.1) {sleep 0.05}
}.should_not raise_error
end
end
stubやmockで任意のメソッドの結果を置き換えられるから、
時間や通信や外部IOなどがあるテストも簡単さ!
def is_over_limit
Time.now > Time.utc(2100,1,1)
end
describe "is_over_limit" do
it "should return false if before limit" do
is_over_limit.should be_false
end
it "should return true if after limit" do
Time.stub(:now => Time.utc(2100,1,1,0,0,1)) # Time.now が Time.utc(2100,1,1,0,0,1) を返すようになる
is_over_limit.should == true
end
end
"-fs" Optionを付けて実行すると、本当に仕様書みたいな感じなるんだ!
% rspec -fs
Array [1,2,3]
should be an instance of Array
should respond to :sort
size
should == 3
Timeout timeout
should raise TimeoutError if time is over
should not raise TimeoutError unless time is over
is_over_limit
should return false if before limit
should return true if after limit
Finished in 0.16024 seconds
7 examples, 0 failures
他、rspecのいいところ
- テストを書き始めるまでが簡単。xUnitにありがちな念仏が一切要らない。これは実際とても有り難い。
- テストRunnerもとても賢い。まあ、rspec とだけ打てば大抵OKだ。あと、Rakefileに組み込むのも1行書くだけでOK。
- タイプ量が少なくて済む。テストって意外と異様な行数になりがちだが、テストコード*量*を減らしつつ可読性を上げられる。可読性が高いことの価値は計り知れないよ。
- 特殊な文法に見えるが、Ruby言語なので自由に色々書くことができる。
RSpecの手始めはやはりこれを読むと良いのではないでしょうか。
やはり「この RSpec には夢があるッ!!」ですよ。