Question

I have playlist entries and episodes. Each playlist entry points to an episode. Each episode does have a duration (in seconds). Now I want to create a playlist entry with factory girl. However I have to calculate the end_time of the playlist entry from the start_time and the duration of the episode. How can I do that? I tried with this code, but does not work:

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

How can I access the duration of the episode that was automatically created because of the episode association?

When executing the spec that uses this factory I get NoMethodError: undefined method 'duration' for nil:NilClass. I assume that's because self.episode is nil.

Here is my factory for 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
Was it helpful?

Solution

One of the variants is to use before(:create) block

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
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top