Dec 21 Rake + Machinist: centralizing data creation

tags: rake machinist | comments

Machinist is my favourite choice for sample data creation in my specs, but you know sometimes you need seed data, e. g. to play with your site in the browser. It is pretty simple to call your blueprints from a rake task that depends on the environment task: the trick is to require your blueprint inside the task body.

# lib/tasks/your_tasks_file.rake
    desc 'generates sample events'
    task :events => :environment do
      # to do this require Rails environment must be loaded since blueprints use models
      require File.expand_path(File.dirname(__FILE__) + "/../../spec/blueprints")

      amount = ENV['AMOUNT'] || 3
      amount.times { Event.make }
    end

#spec/blueprints.rb
require 'machinist/active_record'
# if you are like me and you put your Shams inside a shams.rb, load it with full path
require File.expand_path(File.dirname(__FILE__) + "/shams")
# a model, if Rails is not loaded you get an initialized class exception
Event.blueprint do
# ...
end

this way you centralize your data creation for specs and all others.

Update

after using this approach for a while I am getting to dislike it, since it requires your environment to load machinist/active_record and it could be the case that your environment does not have it as a configured gem.

blog comments powered by Disqus