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_nowend_at { |l| l.start_at + 2.hours }
# Full exampleFactoryGirl.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 endendTags: factory_girl, rails, test
You can leave a response, or trackback from your own site.
