例のごとく既出だけど今回はattribute of subjectについて。rspec-core(2.5.1)/features/subject/attribute_of_subject.feature参考。「it { subject.first.size.should eq 2 }」とかするのやだよね。そんなときはitsを使えばステキになるよって話。
基本的にはシンボルか文字列で指定する
describe Array do context 'when first created' do its(:size) { should eq 0 } its('size') { should eq 0 } end end
% rspec -cfs attribute_of_subject_spec_1.rb Array when first created size should == 0 size should == 0
文字列ならネストした属性も指定できる!
class Person attr_reader :phone_numbers def initialize @phone_numbers = [] end end describe Person do context 'with one phone number (555-1212)' do subject do person = Person.new person.phone_numbers << '555-1212' person end its('phone_numbers.first') { should eq '555-1212' } end end
% rspec -cfs attribute_of_subject_spec_2.rb Person with one phone number (555-1212) phone_numbers.first should == 555-1212 Finished in 0.0017 seconds 1 example, 0 failures
subjectがハッシュなら配列にキーを一個だけ入れて値をテストできる!!
describe Hash do context 'with two items' do subject { {:one => 1, 'two' => 2} } its(:size) { should eq 2 } its([:one]) { should eq 1 } its(['two']) { should eq 2 } end end
% rspec -cfs attribute_of_subject_spec_3.rb Hash with two items size should == 2 [:one] should == 1 ["two"] should == 2 Finished in 0.00441 seconds 3 examples, 0 failures
まとめ
subjectとitsの組み合わせでテストはだいぶシンプルに書けそうですね!って、また順番間違ったな、まだsubjectの解説してないわー。
つづく