くりにっき

フルスタックキュアエンジニアです

rspec-every_itemというgemを作りました

配列の各要素に対してMatcherを適用するためのgemを作りました。

JUniteveryItem Matcherにインスパイアされています。

【追記】

コメントで指摘ありましたがRSpec3だと全く同じ機能の all Matcher があるのでそれを使った方がいいです。

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を使わなかった時

subjectshould の形式に合わせようとするとどうしてもこういう形式になると思います。

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