views:

122

answers:

2

Provided that I have a project factory

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

And that I'm creating instances of project

Factory.build :project
Factory.build :project

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)

Thanks in advance, Best regards.

A: 

There's no built in way to reset a sequence, see the source code here:

http://github.com/thoughtbot/factory_girl/blob/master/lib/factory_girl/sequence.rb

However, some people have hacked/monkey-patched this feature in. Here's an example:

http://www.pmamediagroup.com/2009/05/smarter-sequencing-in-factory-girl/

Winfield
Hello, I've been lurking their source as well and also found that post you linked. Haven't exactly figured out how to solve my issue yet.Factory.sequences behaves [apparently] in a weird way.Factory.build(:project) #=> project 1Factory.build(:project) #=> project 2Factory.sequences.delete(:project)Factory.build(:project) #=> project 3Still trying to figure out why.
DBA
The sequence is giving you a guarenteed unique ID here, not the count of the objects. That behavior is exactly what you should expect. These are used to make sure a name is generated uniquely every time you make an instance from the factory.
Winfield
That's exactly what I'm trying to reset :)
DBA
A: 

I have a similar problem with the db not resetting the sequence to start with 1 after running Cucumber scenario examples. I use factory_girl to seed the test db with 10 or so objects (with a numbered sequence, so id => 1 might have name => name1, etc. ), then I run my first Cucumber scenario example with no problem (db has objects with attributes name1 to name10). When the second scenario example runs, the db factories, but this time the object attributes are name11 to name20.

I would really like the proper way to deal with this. I can set my later scenario examples to test for the later sequence numbers, but that seems a little cheesy to me. Any ideas?

Cucumber::Rails::World.use_transactional_fixtures = true is in the env.rb I run my tests within RubyMine 2.0.2 Hmmm....

Peter Bloom