Ruby-on-rails – How to make factory girl create a date

factory-botrspecruby-on-railsruby-on-rails-4

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

Best Answer

The Faker gem has a very nice method for this:

Faker::Date.between(2.days.ago, Date.today)