LoginSignup
30
30

More than 5 years have passed since last update.

♥♥♥超簡単にFactoryGirlのdefinitionを作る方法♥♥♥

Last updated at Posted at 2012-11-07

rails console で以下を実行し、

class ActiveRecord::Base
  def to_factory_girl
    ignores = %w(id created_at updated_at)
    array = []
    array << "FactoryGirl.define do"
    array << "  factory :#{self.class.model_name.underscore} do"
    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"
    array.join("\n")
  end
  alias_method :to_fg, :to_factory_girl
end

以下を実行すると、

puts User.first.to_factory_girl

こんなのが

FactoryGirl.define do
  factory :user do
    ...
  end
end

あら便利!!!

♥♥♥♥♥♥♥FactoryGirl♥♥♥♥♥♥♥♥

30
30
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
30
30