There are a dozen Rails plugins whose goal is to replace fixtures in testing. Here are a few I can think of:
There are probably others. Which of these plugins do you prefer and why?
I personally use Faker with a custom Factory class. This allows me to create my factories, and populate the generated instances with non-static data.
# spec/factory.rb
module Factory
def self.create_offer(options={})
Offer.create({
:code => Faker::Lorem.words(1),
:expires_on => Time.now + (rand(30) + 1).day
}.merge(options))
end
end
# spec_helper.rb
require 'faker'
require 'spec/factory'
# In the specs
@offer = Factory.create_offer(:code => 'TESTING')
I'll advocate for Fixture Replacement 2. Your default (don't care) model attributes are stored all in one place, db/example_data.rb, and provide quick valid objects. Any attributes you specify upon creation override the default attributes - meaning the data that you care about is in the test, and nothing else.
Your example data can also refer to other default models, which are represented by procs with delayed evaluation, so you can override associations easily when desired.
Version 2 provides a much cleaner definition format, while still providing the magic new_*, create_*, and default_*
methods for every model.
I would avoid any kind of "scenarios" scheme which encourages building more and more test data that's hard to read later. You can create named(custom) objects with FR2, but I've never found a need for it.
P.S. Make sure you consider your unit testing strategy as well - Fixtures and all their analogues are real objects that hit the DB, making for functional or integration tests. I'm currently using RSpec's mocking along with stub_model()
and the latest unit_record gem to disallow DB access.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With