Reputation: 1578
I'm using FactoryGirl to create instances of a date dimension model for a Rails-related gem. My factory looks like this:
FactoryGirl.define do
sequence :next_day do |n|
Date.new(2000,12,31) + n.days
end
factory :date_dimension do
the_date = FactoryGirl.generate(:next_day)
date {the_date.to_s}
calendar_year {the_date.strftime("%Y")}
(...other attributes created similarly to calendar_year)
end
end
Out of frustration I actually built a little test to show what's not working:
describe "working date factories" do
before(:all) do
@date_dimension = FactoryGirl.create(:date_dimension)
@jan_two = FactoryGirl.create(:date_dimension)
end
describe "sequence incrementing" do
it "returns a date dimension object ok" do
@date_dimension.date.should == "2001-01-01"
end
it "returns the next date in the sequence" do
@jan_two.date.should == "2001-01-02"
end
end
end
When I run that test, I get:
working date factories
sequence incrementing
returns a date dimension object ok
returns the next date in the sequence (FAILED - 1)
Failures:
1) working date factories sequence incrementing returns the next date in the sequence
Failure/Error: @jan_two.date.should == "2001-01-02"
expected: "2001-01-02"
got: "2001-01-01" (using ==)
I've read a bunch of other questions related to sequences, but it doesn't seem that I'm making the mistakes identified therein. It's a different (likely dumber) mistake. What is it?
Upvotes: 2
Views: 1237
Reputation: 1578
I finally found an approach that works, and is probably a little better anyway. I still don't understand why the code above doesn't work - if someone can explain that to me (maybe with a reference to a doc or part of the source code), I'll go ahead and accept that answer - this post is just for those who follow. Here's what worked:
FactoryGirl.define do
factory :date_dimension do
sequence(:date) { |n| (Date.new(2000,12,31) + n.days).to_s }
calendar_year { Date.parse(date).strftime("%Y") }
day_of_week { Date.parse(date).strftime("%A") }
end
end
The code above passes this test:
describe "working date factories" do
before(:all) do
@date_dimension = FactoryGirl.create(:date_dimension)
@jan_two = FactoryGirl.create(:date_dimension)
end
describe "sequences" do
it "returns the proper first date in the sequence" do
@date_dimension.date.should == "2001-01-01"
@date_dimension.calendar_year.should == "2001"
@date_dimension.day_of_week.should == "Monday"
end
it "returns the next date in the sequence" do
@jan_two.date.should == "2001-01-02"
@jan_two.calendar_year.should == "2001"
@jan_two.day_of_week.should == "Tuesday"
end
end
end
Upvotes: 1