【问题标题】:Factory girl object with has many through and presence validation具有许多通过和存在验证的工厂女孩​​对象
【发布时间】:2016-12-16 13:32:09
【问题描述】:

我有一个名为 Beats 的模型,它由名称、状态、组、所有者等字段组成。我正在使用 R Spec 编写测试并使用 Factory Girl 进行模拟,我在运行规范时遇到问题,它给出的错误为 ActiveRecord::RecordInvalid: Validation failed: Beat Types can't be blank,我正在验证存在在表单的所有字段中,有一个带有 BeatType 值的下拉列表,在运行规范时也会调用它,将它包含在 Beat 工厂中的方法是什么?

class Beat < ActiveRecord::Base
has_many :beat_beat_types
has_many :beat_types, through: :beat_beat_types

validates :name,:status,:group,:owner,:beat_types presence: true, length: {maximum: 255}
end

class BeatType < ActiveRecord::Base
has_many :beat_beat_types
has_many :beats, through: :beat_beat_types
end

class BeatBeatType < ActiveRecord::Base
belongs_to :beat
belongs_to :beat_type
end


Factory_File of beat

FactoryGirl.define do
factory :beat do
  name
  status
  group
  owner
end
end

【问题讨论】:

  • 您应该在 BeatBeatType 模型而不是 Beat 模型中验证 beat_type

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


【解决方案1】:

你能试试用吗

FactoryGirl.define do
  factory :beat do
  name
  status
  group
  owner
  beat_types { build_list :beat_type, 1 }
end

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-01-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-03-08
    • 2013-05-19
    相关资源
    最近更新 更多