factory_girl_rails

通过一条 generator 命令来生成 夹具 文件,命令如下:

require 'generators/factory_girl'

module FactoryGirl
  module Generators
    class ModelGenerator < Base
      argument :attributes, :type => :array, :default => [], :banner => "field:type field:type"
      class_option :dir, :type => :string, :default => "test/factories", :desc => "The directory where the factories should go"

      def create_fixture_file
        template 'fixtures.rb', File.join(options[:dir], "#{table_name}.rb")
      end
    end
  end

而产生的 template.rb 则是这个

FactoryGirl.define do
  factory :<%= singular_name %> do
<% for attribute in attributes -%>
<%= attribute.name %> <%= attribute.default.inspect %>
<% end -%>
  end
end

再看看其它代码,生成下面两个之一

test/factories
spec/factories

生成的是 Factory (replace fixture)
fixtures.rb => factories.rb

从这可以证实

require 'factory_girl'
require 'rails'

module FactoryGirl
  class Railtie < Rails::Railtie

    initializer "factory_girl.set_fixture_replacement" do
      generators = config.respond_to?(:app_generators) ? config.app_generators : config.generators

      if generators.options[:rails][:test_framework] == :rspec
        generators.fixture_replacement :factory_girl, :dir => 'spec/factories'
      else
        generators.test_framework :test_unit, :fixture => false, :fixture_replacement => :factory_girl
      end
    end

    initializer "factory_girl.set_factory_paths" do
      FactoryGirl.definition_file_paths = [
          File.join(Rails.root, 'factories'),
          File.join(Rails.root, 'test', 'factories'),
          File.join(Rails.root, 'spec', 'factories')
      ]
    end

    config.after_initialize do
      FactoryGirl.find_definitions
    end
  end
end

你可能感兴趣的:(factory_girl_rails)