配列の各要素に対してMatcherを適用するためのgemを作りました。
JUnit の everyItem Matcherにインスパイアされています。
- rubygems http://rubygems.org/gems/rspec-every_item
- github https://github.com/sue445/rspec-every_item
【追記】
コメントで指摘ありましたがRSpec3だと全く同じ機能の all Matcher があるのでそれを使った方がいいです。
- Ruby - 今日から使える!RSpec 3で追加された8つの新機能 - Qiita
all
matcher - Built in matchers - RSpec Expectations - RSpec - Relish
RSpec2だと無いのでこのgemで。
サンプル1
rspec-every_itemを使わなかった時
普通のspecだと配列を検証したい場合はこういう風にeachで回すしかなかったですが
describe "Example 1" do context "Not Using rspec-every_item" do it "should start with 'cure_'" do precure_names = %w(cure_happy cure_sunny cure_peace cure_march cure_beauty) precure_names.each do |name| expect(name).to start_with "cure_" end end end end
rspec-every_itemを使った時
every_item
の中に任意のMatcherを渡すことでループで回す必要がなくなります
describe "Example 1" do context "Using rspec-every_item" do it "should start with 'cure_'" do precure_names = %w(cure_happy cure_sunny cure_peace cure_march cure_beauty) expect(precure_names).to every_item start_with "cure_" # same to # expect(precure_names).to every_item(start_with("cure_")) end end end
サンプル2
これだけだとありがたみが分かりづらいと思うのでもう1つサンプル
rspec-every_itemを使わなかった時
subject
〜 should
の形式に合わせようとするとどうしてもこういう形式になると思います。
describe "Example 2" do def precure_names %w(cure_happy cure_sunny cure_peace cure_march cure_beauty) end subject{ precure_names } context "Not Using rspec-every_item" do its([0]){ should start_with "cure_" } its([1]){ should start_with "cure_" } its([2]){ should start_with "cure_" } its([3]){ should start_with "cure_" } its([4]){ should start_with "cure_" } end end
rspec-every_itemを使った時
すっきりワンライナーで書けるようになります
describe "Example 2" do def precure_names %w(cure_happy cure_sunny cure_peace cure_march cure_beauty) end subject{ precure_names } context "Using rspec-every_item" do it{ should every_item start_with "cure_" } # same to # it{ should every_item(start_with("cure_")) } end end