0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

FactoryGirl用のデータを作るコード

Last updated at Posted at 2017-10-27

開発中に必要になったのでメモ代わりに。
昔作ってたコードが下の感じ。(もしかしたらどこかを参考にしてたのかも)

config/initializers/to_factory.rb
module ActiveRecord
  class Base
    def to_factory
      factory_name = "#{self.class.name.underscore}_#{self.id}"
      result_str = "  factory :#{factory_name}, :class => #{self.class} do \n"
      self.attributes.each do | column, value |
        next if %w(created_at updated_at).include?(column)
        next if value.nil?
        result_str += "    #{column} "
        if value.is_a? Numeric
          result_str += value.to_s
        elsif value.is_a?(TrueClass) ||  value.is_a?(FalseClass)
          result_str += value  ? "true" : "false"
        elsif value.nil?
          result_str += " nil"
        elsif value.is_a?(String)
          result_str += "\"#{value && value.gsub(/"/, "\\\"")}\""
        else
          result_str += "\"#{value}\""
        end 
        result_str += "\n"
      end 
      result_str += "  end\n"
      result_str
    end 
  end 
end

これがあると、以下の様にModel毎にto_factoryできるので、このデータをちょっとspec/factories/に書きたいという時に便利

puts Account.first.to_factory
0
1
0

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
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?