【问题标题】:How to create an associated record within factory girl to pass validations at creation如何在工厂女孩中创建关联记录以在创建时通过验证
【发布时间】:2016-01-22 15:52:55
【问题描述】:

我对 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 的了解非常初级,我无法弄清楚如何让它发挥作用。

【问题讨论】:

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


    【解决方案1】:
    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 }
    

    【讨论】:

    • 还可以查看文档中的 build 函数:github.com/thoughtbot/factory_girl/blob/master/…
    • 当我以这种方式构建它时,我收到以下错误:Failure/Error: subject { help_request } NameError: undefined local variable or method 'help_request' for #&lt;RSpec::ExampleGroups::HelpRequest:0x007ffbb451a380&gt;
    • 你更新你的donation_item 工厂了吗?
    • 实际上,通过工厂中的关联,您甚至可以在规范中使用它(无需明确设置 help_request): let(:donation_item) { FactoryGirl.create(:donation_item) }.. 它已经在做在工厂里。请参阅我参考的文档中的“关联”部分
    • 在你的donation_item.rb 模型中,它是“belong_to :help_request”吗?
    猜你喜欢
    • 2010-12-01
    • 2012-03-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-05-19
    相关资源
    最近更新 更多