FactoryBot一条与许多属性关联的记录

时间:2018-08-30 10:13:04

标签: ruby-on-rails rspec rspec-rails

我有UserAssignmentDepartment模型。 我的Assignment模型具有2个belongs_to关联,其中User模型分别为requestorassignee

UserAssignment模型也依次belongs_to一个部门。

我想对Assignment进行验证,以使assignmentrequestorassignee都属于同一部门。

这是我的模型代码

# app/models/assignment.rb
class Assignment < ApplicationRecord
  belongs_to :requestor, class_name: "User", foreign_key: "requested_by"
  belongs_to :assignee, class_name: "User", foreign_key: "assigned_to"

  belongs_to :department
end

# app/models/user.rb
class User < ApplicationRecord
  has_many :user_departments, class_name: "UserDepartment"
  has_many :departments, through: :user_departments

  belongs_to :department
end

# app/models/department.rb
class Department < ApplicationRecord
  has_many :user_departments, class_name: "UserDepartment"
  has_many :users, through: :user_departments

  has_many :assignments
  has_many :users
end

这是我测试的代码

# spec/factories/assignment.rb
FactoryBot.define do
  sequence(:title) { |n| "Title #{n}" }
  sequence(:description) { |n| "Description #{n}" }

  factory :assignment do
    title
    description
    image { Rack::Test::UploadedFile.new(Rails.root.join('spec/support/Floyd.jpeg'), 'image/jpeg') }
    release_date { DateTime.now >> 1 }
    department { create(:department) }
    requestor create(:user, :bm, department: "I want to use the same department as created in earlier line here")
    assignee create(:user, :mu, department: "I want to use the same department as created in earlier line here")
  end
end

我应该在哪里定义部门,以便可以在所有三个关联中使用同一部门。

2 个答案:

答案 0 :(得分:1)

您尝试过self.department吗?它在我的代码中有效:

# spec/factories/assignment.rb
FactoryBot.define do
  sequence(:title) { |n| "Title #{n}" }
  sequence(:description) { |n| "Description #{n}" }

  factory :assignment do
    title
    description
    image { Rack::Test::UploadedFile.new(Rails.root.join('spec/support/Floyd.jpeg'), 'image/jpeg') }
    release_date { DateTime.now >> 1 }
    department { create(:department) }
    requestor { create(:user, :bm, department: self.department) }
    assignee { create(:user, :mu, department: self.department) }
  end
end

答案 1 :(得分:1)

希望我的问题正确。您要在所有模型上使用相同的部门。 这是您实际上在规范中所做的事情。

describe Foo::Bar do
  before(:each) do
    @department = create(:deparment)
    @assignment = create(:assignment, department: @department)
    @user = create(:user, department: department)
    # ....
  end

但这总是取决于您的整体结构。当assignment是中心模型并且始终设有部门时,您可以执行类似的操作

describe Foo::Bar do
  before(:each) do
    @assignment = create(:assignment)
    @user = create(:user, department: @assignment.department)
    # ....
  end