18
13

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

FactoryGirlでモデルを複数生成するときに便利なやつ

Last updated at Posted at 2015-03-04

FactoryGirl.create

テスト内で保存されたモデルが必要な場合、以下のように書く

let!(:product) do
  FactoryGirl.create(:product)
end

で複数必要な場合はこんな感じに書いてたんですが、これやめたほうがいいです

let!(:products) do
  2.times{ FactoryGirl.create(:product) }
end

何故かというとarrayの順序と、DBから取得した時の順序が保証されないんですよね。

let!(:products) do
  2.times{ FactoryGirl.create(:product) }
end

it 'should equal' do
  expect(products).to eq(Product.all) # これはテストを実行する度に順序が変わる可能性がある
end

じゃあ順序を保証するためにどうするのか?

一瞬、sleep…?と頭によぎりましたがこれもやめましょう

FactoryGirl.create_list

あるよね。そりゃあるよね。

let!(:products) do
  FactoryGirl.create_list(:product, 2)
end

it 'should equal' do
  expect(products).to eq(Product.all)
end

サクセス!

18
13
0

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
18
13

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?