How to make a factory girl create a date?

Update I'm trying to get Factory Girl to populate the “Release Date” field with a date, a random date, frankly any date right now, because I keep getting errors “Validation: release date cannot be empty” when I run my item_pages_spec.rb

After some help below, this is what I have in my .rb factories for position pages, but now I have tried many different things.

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

Ideally, this would be a string that creates different random dates for each instantiated Factory item.

Release date cannot be empty, because I have validates :release_date, presence: true in my product model. Ideally, I would have a check that ensures that any dated date is a date, but also accepts NIL because I will not always have a date available.

Any help is greatly appreciated. I could not find anything specific online about the 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 
+7
ruby-on-rails ruby-on-rails-4 rspec factory-bot
source share
2 answers

Faker gem has a very good way to do this:

 Faker::Date.between(2.days.ago, Date.today) 
+6
source share

This will set the date between now and 2 years later, if necessary, change the parameters (or the extraction method):

 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 
+4
source share

All Articles