与Factory Girl相关的属性

时间:2014-04-21 08:42:39

标签: ruby-on-rails factory-bot

我有playlist entriesepisodes。每个播放列表条目都指向一集。每集都有一段持续时间(以秒为单位)。现在我想创建一个带工厂女孩的播放列表条目。但是,我必须从end_timestart_time计算播放列表条目的duration of the episode。我怎样才能做到这一点?我尝试使用此代码,但无效:

FactoryGirl.define do
  factory :playlist_entry_episode, class: PlaylistEntry do
    start_time Faker::Business.credit_card_expiry_date
    episode
    end_time {start_time + self.episode.duration}
    premiere false
    channel_playlist
  end
end

如何访问由于episode关联而自动创建的剧集的持续时间?

执行使用此工厂的规范时,我得到NoMethodError: undefined method 'duration' for nil:NilClass。我认为这是因为self.episodenil

这是episode的工厂:

FactoryGirl.define do

  factory :episode do
    title Faker::Lorem.paragraph(1)
    link Faker::Internet.url
    pub_date Faker::Business.credit_card_expiry_date
    guid Faker::Lorem.characters(10)
    subtitle Faker::Lorem.paragraph(1)
    content Faker::Lorem.paragraph(5)
    duration Faker::Number.number(6)
    flattr_url Faker::Internet.url
    tags Faker::Lorem.paragraph(1)
    icon_url Faker::Internet.url
    audio_file_url Faker::Internet.url
    cached false
    local_path ""
    filesize Faker::Number.number(6)
    podcast
  end
end

1 个答案:

答案 0 :(得分:3)

其中一个变体是使用before(:create)

FactoryGirl.define do
  factory :playlist_entry_episode, class: PlaylistEntry do
    start_time Faker::Business.credit_card_expiry_date
    episode
    premiere false
    channel_playlist

    before(:create) do |entry|
      entry.end_time = entry.start_time + entry.episode.duration
    end
  end
end