Factory Girl!
Last month, factory_girl was featured in the RailsEnvy podcast. factory_girl is one of the best things that happened to my Rails TDD/BDD life. It's the only other thing I use with rspec and rspec-rails, though I'm pretty open, so suggestions to make making tests easier are very much welcome. The one con is that factory_girl is tied to ActiveRecord, but it's not really an issue for me because all my non-personal projects use AR. If you are still using fixtures, take a look at factory_girl. It's really nice. Anyway...
factory_girl has a nice feature that lets you define a sequence which you can use to generate unique things. For example, to generate an email address, you can do this (taken from factory_girl's rdoc):
# define a sequence
Factory.sequence :email {|n| "user#{n}@example.com" }
# calling the `next` method
Factory.next :email
# => "user1@example.com"
Factory.next :email
# => "user2@example.com"
However, one of the behaviors in my projects that is not so easy to do with factory_girl is generating unique strings that cannot contain numbers.
I added this behavior in my projects using the following monkey patch I made.
class Factory
def self.sequence(name, initial_value = 1, &block)
self.sequences[name] = Sequence.new(initial_value, &block)
end
class Sequence
def initialize(initial_value = 1, &proc)
@proc = proc
@value = initial_value
end
def next
prev, @value = @value, @value.next
@proc.call(prev)
end
end
end
This would make the sequence more generic such that anything that has a next method can be passed. A string object has next method so we can use that to generate unique and sequential strings, with no numeric characters. For example,
Factory.sequence :email, 'aaaa' {|s| "user#{s}@example.com"}
# calling the `next` method
Factory.next :email
# => "useraaaa@example.com"
Factory.next :email
# => "useraaab@example.com"
We can even implement a PrimeSequence class and pass it to Factory.sequence to generate a prime number sequence. ;)
Last night, I forked factory_girl in GitHub and applied this monkey patch to the fork. The clone url is git://github.com/teem/factory_girl.git. You can check it out here. I've included specs as well, which has the prime number sequence I mentioned earlier.
Hope this helps you in making the world a better place.
P.S. I recently found Rick's model_stubbing. I haven't looked at it so atm, I have no idea how it works, but the features look promising.



