【问题标题】:Rails FactoryGirl for model that belongs_to 2 other modelsRails FactoryGirl 用于属于_to 2 个其他模型的模型
【发布时间】:2018-04-19 15:20:26
【问题描述】:

我有 3 个这样的模型:

# model/timeline.rb
class Timeline
  belongs_to :series
  belongs_to :creator
end

def series_belongs_to_creator
  if creator_id
    creator = Creator.find_by id: creator_id
    related_series = creator.series.find_by id: series_id
    errors.add(:series_id, :not_found_series) unless related_series
  end
end

# model/creator.rb
class Creator
  has_many :timelines
  has_many :series, through: :contents
end

# model/series.rb
class Series
  has_many :timelines
  has_many :creators, through: :contents
end

这不是多对多关系,timelines 表在另一个字段旁边有两个字段 creator_idseries_id。创建时间轴时必须输入creator_idseries_id,并且我有一个方法series_belongs_to_creator 来验证series_id 必须属于creator_id 才能创建成功。 那么如果使用 FactoryGirl,我应该如何为时间线模型编写工厂。我对 Rails 中的单元测试感到很困惑。

【问题讨论】:

    标签: ruby-on-rails unit-testing factory-bot


    【解决方案1】:

    如果您使用的是 Rails 5,则必须记住 belongs_to 在默认情况下不再是可选的:https://blog.bigbinary.com/2016/02/15/rails-5-makes-belong-to-association-required-by-default.html

    所以creator_id 将始终需要存在,除非您指定关系是可选的。

    对于工厂,您最终会得到这样的结果(FactoryGirl 最近更名为 FactoryBot): http://www.rubydoc.info/gems/factory_bot/file/GETTING_STARTED.md#Associations

    FactoryBot.define do
      factory :timeline do
        creator
        series
      end
    end
    
    
    FactoryBot.define do
      factory :creator do
        ...
      end
    end
    
    
    FactoryBot.define do
      factory :series do
        ...
      end
    end
    

    【讨论】:

      猜你喜欢
      • 2015-02-03
      • 2016-04-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-04-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多