Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
ActiveRecord extension to print FactoryGirl definition!
class ActiveRecord::Base
# Usage:
#
# > puts User.first.to_factory_girl
# FactoryGirl.define do
# factory :user do
# ...
# end
# end
# # Usage: FactoryGirl.create(:user, ...)
def to_factory_girl
ignores = %w(id created_at updated_at)
array = []
array << "# encoding: utf-8"
array << "FactoryGirl.define do"
factory_name = self.class.model_name.underscore
unless factory_name =~ %r|/|
array << " factory :#{factory_name} do"
else
factory_name.gsub!('/', '_')
array << " factory :#{factory_name}, :class => #{self.class.name} do"
end
attributes.each do |key, value|
next if ignores.include?(key)
if key =~ /_id$/
array << " association :#{key.gsub(/_id$/, '')}"
else
array << " #{key} #{value.inspect}"
end
end
array << " end"
array << "end"
usage = ""
usage << "# Usage: FactoryGirl.create(:#{factory_name}"
attributes.each do |key, value|
next if ignores.include?(key)
if key =~ /_id$/
factory_name = key.gsub(/_id$/, '')
usage << ", #{factory_name}: FactoryGirl.create(:#{factory_name})"
else
usage << ", #{key}: #{value.inspect}"
end
end
usage << ")"
array << usage
array.join("\n")
end
alias_method :to_fg, :to_factory_girl
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.