How to make factory girl create a date?
Asked Answered
A

2

10

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
Aircondition answered 30/9, 2013 at 11:19 Comment(3)
release_date { rand(1..100).days.from_now } note that you can insert any range into the rand function. Btw, read the doc pleaseAlong
I did read the document and tried some solutions from it. It seems the problem is with my validator as neither your solution, nor the one below are passing my tests. I'll have to find a better alternative to "validates "release_date, presence: true" as I'm sure both your should work. Thank you.Aircondition
mind posting your model and a snippet from your test code?Along
D
9

The Faker gem has a very nice method for this:

Faker::Date.between(2.days.ago, Date.today) 
Detta answered 16/1, 2015 at 10:3 Comment(0)
B
4

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
Biogen answered 30/9, 2013 at 11:25 Comment(2)
That looks great but it's still give me the "release date can't be blank" error. Very confused. I'd guess this means my problem is elsewhere.Aircondition
the factory I wrote is valid, cant tell why your validator complainsBiogen

© 2022 - 2024 — McMap. All rights reserved.