创建模型后,FactoryBot可以生成工厂吗?

问题描述 投票:45回答:7

[在将dev_factor_bot_rails gem包含在您的dev和Gemfile中的测试块中时,rails将在生成模型时自动生成工厂。

生成模型后,有没有办法生成工厂?


Eduardo Santana's ANSWER SHOULD BE CORRECT

注意:FactoryBot以前被命名为FactoryGirl

ruby-on-rails ruby factory-bot
7个回答
15
投票

--fixture-replacement选项可让您告诉Rails为构建测试数据生成什么。您可以在config/application.rb文件中将此设置为默认值,如下所示:

config.generators do |g|
  g.fixture_replacement :factory_girl
end

138
投票

首先,查看源项目以了解其实现方式:

https://github.com/thoughtbot/factory_bot_rails/blob/master/lib/generators/factory_bot/model/model_generator.rb

之后,尝试猜测其工作方式:

rails g factory_bot:model Car name speed:integer

结果是:

create  test/factories/cars.rb

和内容:

# Read about factories at https://github.com/thoughtbot/factory_girl

FactoryBot.define do
   factory :car do
     name "MyString"
     speed 1
   end
end

记住,当您使用滑轨g时,始终可以使用滑轨d撤消它

rails d factory_bot:model Car name speed:integer

注意:FactoryBot以前被命名为FactoryGirl


7
投票

我为此https://github.com/markburns/to_factory拥有一颗宝石


2
投票

这不是答案,但由于我无法发表评论:我认为您可以使用它来解决部分问题。您可以使用名为schema_to_scaffold的gem来生成factory_girl:model命令字符串。它输出:

[rails生成factory_girl:model用户fname:string lname:string bdate:date电子邮件:string encryption_password:string

来自您的schema.rb或重命名的schema.rb。

检查herehere


1
投票

这对我有用rails g factory_bot:model User运行命令或只是将命令放出来。您仍然必须填写值。

@run_command        = true
@force              = true
@columns_to_ignore  = %w[id created_at update_at]
@tables_to_ignore = %w[schema_migrations ar_internal_metadata]
tables = ActiveRecord::Base.connection.tables.reject{|t| (@tables_to_ignore || []).include?(t)}

tables.each do |table|
  klass = table.singularize.camelcase.constantize
    command = "rails g factory_bot:model #{klass.to_s} #{klass.columns.reject do |c|
      (@columns_to_ignore || []).include?(c.name)
    end.map do |d|
      "#{d.name}:#{d.sql_type == 'jsonb' ? 'json' : d.type}"
  end.join(' ')}"
  command << ' --force' if @force
  puts command
  puts %x{#{command}} if @run_command
  puts (1..200).to_a.map{}.join('-')
end

0
投票

如果使用的是RSpec,并且想在spec/factories目录中创建工厂,请使用以下命令

rails g factory_girl:model Car name speed:integer --dir spec/factories

-1
投票

这里有一些不错的答案,但是另一种选择是使用stepford。对于某些使用具有外键约束的架构的项目,deep_ *方法等可能会有所帮助,这是通过命令行生成工厂的简单方法。

© www.soinside.com 2019 - 2024. All rights reserved.