Ruby on rails FactoryGirl序列不递增
我正在使用FactoryGirl为Rails相关的gem创建日期维度模型的实例。我的工厂是这样的:Ruby on rails FactoryGirl序列不递增,ruby-on-rails,factory-bot,Ruby On Rails,Factory Bot,我正在使用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} cale
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 ==)
我已经读了很多关于序列的其他问题,但似乎我没有犯其中指出的错误。这是一个不同的(可能更愚蠢的)错误。这是什么?我终于找到了一种有效的方法,而且可能更好一些。我仍然不明白为什么上面的代码不起作用-如果有人能向我解释(可能是引用了一个文档或部分源代码),我会继续接受这个答案-这篇文章只适合那些关注的人。以下是有效的方法:
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
我真的无法重现你的问题。我试着定义一个几乎相同的工厂,它在顺序上工作得很好。然后我怀疑这可能与在:date_维度工厂中使用块和局部变量有关,但没有结果。。对我来说,它工作得很好..嗯,计数器是从0开始的吗?我的理论是,如果第一个例子通过,这表明计数器是从1开始的,因为2000年12月31日+1.day应该是2001年1月1日。它通过了,所以我认为这表明计数器从1开始。