FactoryGirl: build と createの違い
違い
build
Build()
メソッドはインスタンスをメモリ上にのみ記録する。create
create()
メソッドはテストデータベースにも保存して、データを永続化させる。
使い分け
- DBに書き込むのは時間がかかるので、DBに保存する必要がないときは
build()
を使う。 - 属性のチェックだけの場合も
build()
で済む。
具体例
let(:user) { User.new(name: "foo", email: "foo@example.com") } let(:user) { User.create(name: "foo", email: "foo@example.com") }
の代わりに
# spec/models/user_spec.rb let(:user) { FactoryGirl.build(:user) } let(:user) { FactoryGirl.create(:user) }
FactoryGirlでの定義
# spec/factories.rb FactoryGirl.define do factory :user do name "foo" email "foo@example.com" end end
リンク
参照元
FactoryGirlの使い方