Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Preferred fixture replacement plugin in Rails? [closed]

There are a dozen Rails plugins whose goal is to replace fixtures in testing. Here are a few I can think of:

  • fixture replacement
  • factory girl
  • factories and workers
  • rails scenarios
  • fixture-scenarios
  • object daddy

There are probably others. Which of these plugins do you prefer and why?

like image 713
gsmendoza Avatar asked Oct 17 '08 10:10

gsmendoza


2 Answers

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')
like image 106
Codebeef Avatar answered Oct 02 '22 15:10

Codebeef


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.

like image 35
James Baker Avatar answered Oct 02 '22 16:10

James Baker