Gui*_*ody 43 ruby ruby-on-rails factory-bot
当您在dev和Gemfile中的测试块中包含factory_girl_rails gem时,rails会在生成模型时自动生成工厂.
生成模型后有没有办法生成工厂?
Edu*_*ana 136
首先,查看源项目以了解它是如何实现的:
之后,尝试猜测它是如何工作的:
rails g factory_girl:model Car name speed:integer
Run Code Online (Sandbox Code Playgroud)
结果是:
create test/factories/cars.rb
Run Code Online (Sandbox Code Playgroud)
内容:
# Read about factories at https://github.com/thoughtbot/factory_girl
FactoryGirl.define do
factory :car do
name "MyString"
speed 1
end
end
Run Code Online (Sandbox Code Playgroud)
请记住,当您使用rails g时,您可以随时使用rails d撤消它
rails d factory_girl:model Car name speed:integer
Run Code Online (Sandbox Code Playgroud)
cjh*_*eal 16
该--fixture-replacement选项将让您告诉rails生成用于构建测试数据的内容.您可以将其设置为config/application.rb文件中的默认值,如下所示:
config.generators do |g|
g.fixture_replacement :factory_girl
end
Run Code Online (Sandbox Code Playgroud)
这对我来说很有效,使用rails g factory_bot:model 用户可以运行命令,也可以只是将命令输出。您仍然需要填写该值。
@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
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
19308 次 |
| 最近记录: |