Kinopyo Blog

プログラマとしてRuby, Rails, iPhone, iPad,Macなどなどと向き合う日々のログポース

FactoryGirl: 既に定義した値をベースにした値を設定する方法

2012年01月26日 by kinopyo | Ruby


FactoryGirlで既に定義した値を使おうとする時の方法です。

例えばLessonというクラスのstart_atとend_atの属性があり、start_atを定義した後はend_atをその2時間後に定義したい場合、ブロックでパラメータを渡せばそこでstart_atにアクセスできるようになります。

# Say you have two columns: start_at, end_at
# When start_at is defined, you want end_at's value based on the start_at
# Here is the solution, passing a block to get the object of the context.

start_at Random.new.rand(14..45).days.from_now
end_at { |l| l.start_at + 2.hours }

# Full example
FactoryGirl.define do
  factory :lesson do
    sequence(:title) { |n| "lesson title#{n}" }
    sequence(:description) { |n| "lesson description#{n}" }
    capacity 6
    start_at Random.new.rand(14..45).days.from_now
    end_at { |l| l.start_at + 2.hours }
    price [5000, 5100, 5200, 5300, 5500, 6000].sample
  end
end
view raw gistfile1.rb This Gist brought to you by GitHub.

Tags: , ,

You can leave a response, or trackback from your own site.

関連記事