如何在工厂女孩中创建关联记录以在创建时传递验证

时间:2016-01-22 15:52:55

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

我对FactoryGirl知之甚少,并且只创建了没有关联的单记录工厂。这里有两个我现在用于相关模型的工厂:

factory :help_request do
    name "Mrs. Bourque's holiday party"
    description "We need volunteers to help out with Mrs. Bourque's holiday party."
end

factory :donation_item do
    name "20 Cookies"
end

每当我需要关联两条记录时,我会在事后用rspec执行此代码:

require 'spec_helper'

describe HelpRequest do
  let(:help_request) { FactoryGirl.create(:help_request) }
  let(:donation_item) { FactoryGirl.create(:donation_item) }

  subject { help_request }

  before {
    donation_item.help_request_id = help_request.id
    donation_item.save!
  }

通常情况下这已经奏效,但现在我确认至少有一个donation_item尚未标记为销毁:

class HelpRequest < ActiveRecord::Base      has_many :events
  has_many :donation_items, dependent: :destroy
  validate :check_donation_items?

  def has_donation_items?
    self.donation_items.collect { |i| !i.marked_for_destruction? }.any?
  end

  def check_donation_items?
    if !has_donation_items?
      errors.add :a_help_request, "must have at least one item."
    end
  end

当我运行模型测试时,所有内容都会失败并显示以下内容:

 Failure/Error: let(:help_request) { FactoryGirl.create(:help_request) }
 ActiveRecord::RecordInvalid:
   Validation failed: A help request must have at least one item.

如何在help_request创建时将工作中的捐赠项目关联起来?我看到其他似乎相关的答案,但由于我对FactoryGirl的理解是如此简陋,我无法弄清楚如何使其发挥作用。

1 个答案:

答案 0 :(得分:2)

factory :donation_item do
    name "20 Cookies"
    help_request
end

factory :help_request do
    name "Mrs. Bourque's holiday party"
    description "We need volunteers to help out with Mrs. Bourque's holiday party."
end

然后在你的规范中:

let(:donation_item) { FactoryGirl.create(:donation_item, help_request: FactoryGirl.create(:help_request)) }

修改 不要在:donation_item工厂中包含help_request个关联,并在测试中执行此操作:

let(:help_request) do
  help_request = build(:help_request)
  help_request.donation_items << build(:donation_item)
  help_request.save!
  help_request
end

subject { help_request }