LoginSignup
5
4

More than 5 years have passed since last update.

RSpecのfeatureテストで、複数の商品のテストデータ作成を簡潔にする方法

Last updated at Posted at 2018-11-22

はじめに

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]) } }


(以下省略)
5
4
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
5
4