LoginSignup
1
3

More than 1 year has passed since last update.

Ruby on Rails | FactoryGirl で特定のフィールドに依存した別のフィールドを作る

Last updated at Posted at 2017-01-18

コード例

名前と名字を元に氏名を作りたい場合。

FactoryGirl.define do
  factory :person, class: 'Person' do
    first_name { 'Bill' }
    last_name  { 'Wyman' }
    full_name  { "#{self.person_first_name} #{self.person_last_name}" }
  end
end

動作例

build でも

FactoryGirl.build :person

# => <Person:0x007ff1e2f53cd8
# first_name: "Bill",
 #last_name: "Wyman",
 #full_name: "Bill Wyman",

create でも

FactoryGirl.create :person

# => <Person:0x007ff1e2fa4868
# first_name: "Bill",
# last_name: "Wyman",
# full_name: "Bill Wyman",

環境

  • ruby 2.3.1
  • factory_girl (4.7.0)
  • factory_girl_rails (4.7.0)

チャットメンバー募集

何か質問、悩み事、相談などあればLINEオープンチャットもご利用ください。

Twitter

1
3
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
1
3