如何使用FactoryGirl简化复杂的创作

时间:2015-10-26 09:29:46

标签: ruby-on-rails factory-bot

在我的应用中,我有这种结构:

Organization
  -- members (through many to many table)
  -- projects
    -- boards
      -- cards
        -- owner (user that must be a member of organization)

很多测试发生在卡片周围,因此我最终会使用过多毛茸茸的设置方法,因为card必须有organizationprojectboard及其所有者

在这种情况下,您如何为card实施一个体面的工厂?

目前的解决方案我想清理

注意我错过了与项目的board连接,主板上有列,理想情况下,卡应该放在其中一列上。

FactoryGirl.define do
  factory :card do
    _project = FactoryGirl.create(:project)
    project _project
    subject { Faker::Hacker.say_something_smart }
    author _project.organization.members.first
  end

  factory :user do
    first_name { Faker::Name.first_name }
    last_name { Faker::Name.last_name }
    email { Faker::Internet.email }
    password 'mypassword'
    password_confirmation 'mypassword'
  end

  factory :project do
    name Faker::Internet.domain_name
    organization
  end

  factory :organization do
    name Faker::Company.name

    after(:create) do |post|
      2.times {
        post.members << FactoryGirl.create(:user)
      }
    end
  end

end

1 个答案:

答案 0 :(得分:1)

你可以试试这个结构

FactoryGirl.define do
 factory :project
 end
end

FactoryGirl.define do
 factory :organization do
 end
end

FactoryGirl.define do
  factory :board
   project
  end
 end

FactoryGirl.define do
 factory :owner do
  organization
 end
end

FactoryGirl.define do
 factory :card do
  board
  owner
  transient do
   owner_organization false
  end

  after(:create) do |card, evaluator|
   card.owner.update_attributes(organization: evaluator.organization) if evaluator.organization
  end
 end
end

然后你可以尝试以下方法

  • 项目,董事会和所有者的默认值FacctoryGirl.create(:card)
  • 具有瞬态属性的自定义值FactoryGirl.create(:card, owner_organization: Organization.last)
  • 自定义值FactoryGirl.create(:card, board: FactoryGirl.create(:board, project: FactoryGirl.create(:project))) y