Created
November 7, 2012 05:54
-
-
Save jugyo/4029778 to your computer and use it in GitHub Desktop.
ActiveRecord extension to print FactoryGirl definition!
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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