LoginSignup
12
10

More than 5 years have passed since last update.

FactoryGirlの名前空間と上書き

Posted at

torshinorさんの Factory Girl 3.x メモ が超絶わかりやすくまとまっているので、基本的にはそれだけで事足ります。
その中のFactoryGirl.modifyの具体例とか補足など。

名前空間は1つ

FactoryGirlは基本的に名前空間が1つなので、同じ名前の定義が(別ファイルでも対象クラスが違っても)複数あると
FactoryGirl::DuplicateDefinitionErrorで落ちます。

spec/factories/user.rb
FactoryGirl.define do
  factory :test_data, class: User do
    name "Suzuki"
  end
end
spec/factories/shop.rb
FactoryGirl.define do
  factory :test_data, class: Shop do
    tel "0120-888-888"
  end
end

  #=> FactoryGirl::DuplicateDefinitionError

gem 'factory_girl_rails'が定義された環境だと、
  rspec **だけでなくrails sでもrails cでもrake **でも落ちます。

FactoryGirl.modifyで上書き

FactoryGirl.modifyを使えば上書きできます。

spec/factories/user.rb
FactoryGirl.define do
  factory :test_data, class: User do
    name "Suzuki"
  end
end

FactoryGirl.modify do
  factory :test_data, class: User do
    name "Sato"
  end
end

$ FactoryGirl.build(:test_data).name #=> "Sato"

※ちなみに、defineされてないものに対してmodify定義すると
  Factory not registered: test_data (ArgumentError)で落ちます。

使いどころ

Rails Engineを使っていて、一部の子アプリでだけ上書きしたい、とかいう場合に使えそう。

spec/factories/user.rb
FactoryGirl.define do
  factory :test_data, class: User do
    name "Suzuki"
  end
end
child_a/spec/factories/user.rb
FactoryGirl.modify do
  factory :test_data, class: User do
    name "Sato"
  end
end
child_b/spec/factories/user.rb
FactoryGirl.modify do
  factory :test_data, class: User do
    name "Yamada"
  end
end
12
10
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
12
10