DiyActiveRecordFixtures

January 30, 2019
Originally posted July 9th, 2012
Updated Jan 30th, 2019

DIY fixtures - forget factory_bot and their ilk. Usually I'll place these in lib/fixtures/fixtures.rb because they can be used in rake tasks and other not-specifically-test places. Add a requires to this file in test_helper or spec_helper and also in whatever rake tasks or scripts want to use them.

It's a little less aesthetically pleasing, but does the same job, is easier to debug, and has fewer potential hang-ups.


require 'faker'

class BaseFixture
def self.create(opts={})
fixture = self.new(opts)
fixture.save!
fixture
end
end

class CustomerFixture < BaseFixture
def self.new(opts={})
Customer.new(opts.reverse_merge(:name => Faker::Name.name))
end
end


For a more elaborate version, plus specs comparing this approach with factory_bot and machinist, plus demonstrating some of the challenges they have, see github.com/chrismo/ar_fixture. The file with the specific fixture code is in github.com/chrismo/ar_fixture/blob/master/lib/fixtures/fixtures.rb

If you have a Rails application where you frequently run into the problem of seed.rb being broken because it's not kept up-to-date, re-using this DIY fixture approach in seed.rb and your tests can help keep things current.

tags: ComputersAndTechnology
comments powered by Disqus