我正在使用FactoryGirl为与Rails相关的gem创建日期维度模型的实例。我的工厂看起来像这样:
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
出于沮丧,我实际上建立了一个小测试,以显示什么不起作用:
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
当我进行测试时,我得到:
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 ==)
我已经阅读了一系列与序列有关的其他问题,但似乎我没有在其中发现错误。这是一个不同的(可能是笨蛋)错误。它是什么?
答案 0 :(得分:1)
我终于找到了一种有效的方法,无论如何可能会好一些。我仍然不明白为什么上面的代码不起作用 - 如果有人可以向我解释(可能是对文档或部分源代码的引用),我会继续并接受这个答案 - 这篇文章只适合那些关注的人。这是有效的:
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
上面的代码通过了这个测试:
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