Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make factory girl create a date?

Updated I'm trying to get Factory Girl to fill my "Release Date" field with a date, a random date, frankly any date right now because I keep getting " Validation failed: Release date can't be blank" errors when I run my item_pages_spec.rb

After some help below, his is what I have in my factories.rb for item pages but I've tried a lot of different things now.

  factory :item do
    sequence(:name)  { |n| "Item #{n}" }
    release_date { rand(1..100).days.from_now }
  end

Ideally it would be a line that creates different random dates for each factory made instance of an item.

The release date can't be blank because I have validates :release_date, presence: true in my item model. Ideally I'd have a validation there that makes sure any date supplied IS a date but also accepts NIL because I won't always have a date available.

Any help much appreciated. I couldn't find anything specific online about factory girl and dates.

Model

class Item < ActiveRecord::Base
validates :name, presence: true, length: { maximum: 50 }
validates :release_date, presence: true

end

Item_pages_spec.rb

    require 'spec_helper'

describe "Item pages" do

  subject { page }

 describe "Item page" do
   let(:item) { FactoryGirl.create(:item) }
   before { visit item_path(item) }

   it { should have_content(item.name) }
   it { should have_title(item.name) }
 end
end
like image 447
Ossie Avatar asked Sep 30 '13 11:09

Ossie


2 Answers

The Faker gem has a very nice method for this:

Faker::Date.between(2.days.ago, Date.today) 
like image 155
macbury Avatar answered Sep 18 '22 09:09

macbury


This will set a date between now and 2 years from now, adjust params (or extract method) if needed:

factory :item do
  sequence(:name)  { |n| "Item #{n}" }
  release_date do
    from = Time.now.to_f
    to   = 2.years.from_now.to_f
    Time.at(from + rand * (to - from))
  end
end
like image 32
apneadiving Avatar answered Sep 20 '22 09:09

apneadiving