はじめに
RSpecのfeatureテストで、複数の商品のテストデータ(それぞれ違う商品名)を作成する際に役立つ方法を紹介します。
いままで
下記のように各商品ごとに1つ1つテストデータを書いていました。
spec/features/product_spec.rb
RSpec.feature "Hogehoge::Products", type: :feature do
given(:cap_taxon) { create :taxon, name: "Cap" }
given!(:caps_1) { create(:product, name: "Ruby Cap 1", taxons: [cap_taxon]) }
given!(:caps_2) { create(:product, name: "Ruby Cap 2", taxons: [cap_taxon]) }
given!(:caps_3) { create(:product, name: "Ruby Cap 3", taxons: [cap_taxon]) }
given!(:caps_4) { create(:product, name: "Ruby Cap 4", taxons: [cap_taxon]) }
given!(:caps_5) { create(:product, name: "Ruby Cap 5", taxons: [cap_taxon]) }
(以下省略)
変更後
n.times.collectを使うことで、1行で書けるようになりました!
spec/features/product_spec.rb
RSpec.feature "Hogehoge::Products", type: :feature do
given(:cap_taxon) { create :taxon, name: "Cap" }
given!(:cap_product) { 5.times.collect { |i| create(:product, name: "Ruby Cap #{i}", taxons: [cap_taxon]) } }
(以下省略)