简体   繁体   中英

factory_girl singleton dependencies

I have an interesting scenario.

I have a task model which has a task status :

class Task < ActiveRecord::Base
 belongs_to :task_status
end

class TaskStatus < ActiveRecord::Base
 has_many :tasks
end

I define factories for both of those models for my testing:

FactoryGirl.define do
  factory :task do
    title  'sample task'
    task_status { |task| task.association(:actvice_status) }
  end
end

FactoryGirl.define do
  factory :active_status do
    status_value "ACTIVE"
  end
end

The problem comes when creating instances for testing:

10.times do
  task = FactoryGirl.create(:task)
end

This will create 10 tasks and also 10 "ACTIVE" task statuses. In reality, I need just 1 task status, which the task can reference. Any ideas?

The easiest thing:

active = create(:active_status)
tasks = []
10.times do
    tasks << create(:task, task_status: active)
end

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM