Help us understand the problem. What is going on with this article?

単一テーブル継承を使った Model の FactoryGirl 定義方法

More than 5 years have passed since last update.

単一テーブル継承 を利用している以下のような Model が存在しているとします。

app/models/user.rb
class User < ActiveRecord::Base
end
app/models/girl.rb
class Girl < User
end
app/models/boy.rb
class Boy < User
end

この場合 FactoryGirl は以下のように定義します。

spec/factories/users.rb
FactoryGirl.define do
  factory :user do
    name 'Anonymous'
    age  18
  end
end
spec/factories/girls.rb
FactoryGirl.define do
  factory :girl, parent: :user, class: 'Girl'
end
spec/factories/boys.rb
FactoryGirl.define do
  factory :boy, parent: :user, class: 'Boy'
end

これでサブクラスのオブジェクトを正しく生成できます!

FactoryGirl.build(:girl, name: '戦場ヶ原ひたぎ')
#=> #<Girl:0x00000000000000 name: "戦場ヶ原ひたぎ", age: 18, type: "Girl">

ポイントは以下の 2 つです。

  1. サブクラスの factory の parent オプションでスーパークラスの factory を指定すること。
  2. サブクラスの factory の class オプションで自身の class を指定すること。
    • これがないと Factory.build(:girl) や Factory.create(:girl) の返り値がスーパークラスの型 (この例では User 型) になってしまいます。
QUANON
あんた、マジなんだな?
http://quanon.github.io/
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
No comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
ユーザーは見つかりませんでした