如何重置factory_girl序列? [英] How can I reset a factory_girl sequence?
问题描述
提供了我的项目工厂
Factory.define :project do |p|
p.sequence(:title) { |n| "project #{n} title" }
p.sequence(:subtitle) { |n| "project #{n} subtitle" }
p.sequence(:image) { |n| "../images/content/projects/#{n}.jpg" }
p.sequence(:date) { |n| n.weeks.ago.to_date }
end
我正在创建项目实例
Factory.build :project
Factory.build :project
这一次,下次我执行Factory.build(:project)时,我将收到一个Project实例,其标题设置为"project 3 title",依此类推.不足为奇.
By this time, the next time I execute Factory.build(:project) I'll receive an instance of Project with a title set to "project 3 title" and so on. Not surprising.
现在说我想在此范围内重置我的计数器.像这样:
Now say that I wish to reset my counter within this scope. Something like:
Factory.build :project #=> Project 3
Factory.reset :project #=> project factory counter gets reseted
Factory.build :project #=> A new instance of project 1
实现此目标的最佳方法是什么?
What would be the best way to achieve this?
我当前正在使用以下版本:
I'm currently using the following versions:
factory_girl(1.3.1) factory_girl_rails(1.0)
factory_girl (1.3.1) factory_girl_rails (1.0)
预先感谢, 最好的问候.
Thanks in advance, Best regards.
推荐答案
大家好, 在跟踪源代码之后,我终于找到了解决方案.如果您使用的是factory_girl 1.3.2(这是我撰写本文时的最新版本),则可以将以下代码添加到factory.rb文件的顶部:
Hey everybody, After tracing my way through the source code, I have finally come up with a solution for this. If you're using factory_girl 1.3.2 (which was the latest release at the time I am writing this), you can add the following code to the top of your factories.rb file:
class Factory
def self.reset_sequences
Factory.factories.each do |name, factory|
factory.sequences.each do |name, sequence|
sequence.reset
end
end
end
def sequences
@sequences
end
def sequence(name, &block)
s = Sequence.new(&block)
@sequences ||= {}
@sequences[name] = s
add_attribute(name) { s.next }
end
def reset_sequence(name)
@sequences[name].reset
end
class Sequence
def reset
@value = 0
end
end
end
然后,在Cucumber的env.rb中,只需添加:
Then, in Cucumber's env.rb, simply add:
After do
Factory.reset_sequences
end
我假设如果在rspec测试中遇到相同的问题,则可以在:each方法之后使用rspecs.
I'd assume if you run into the same problem in your rspec tests, you could use rspecs after :each method.
目前,此方法仅考虑工厂中定义的序列,例如:
At the moment, this approach only takes into consideration sequences defined within a factory, such as:
Factory.define :specialty do |f|
f.sequence(:title) { |n| "Test Specialty #{n}"}
f.sequence(:permalink) { |n| "permalink#{n}" }
end
我尚未编写处理代码:Factory.sequence ...
I have not yet written the code to handle: Factory.sequence ...
希望这可以帮助所有其他无法理解的人,为什么世界上的工厂女工为什么不提供这种服务呢?也许我会分叉github项目并使用此修复程序提交拉取请求,因为它不会更改其任何内部功能.
Hope this helps all the other frustrated people out there who cannot understand why in the world factory girl doesn't provide this already. Maybe I'll fork the github project and submit a pull request with this fix since it doesn't change any of their internal functionality.
-安德鲁
这篇关于如何重置factory_girl序列?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!