--- title: factory_bot tags: 專案實作分享 相關 --- ## <font color=red>**factory_bot** </font> gem 'factory_bot_rails', '~> 6.2' gem 'faker', '~> 2.19' bundle config/application.rb 加入 ```ruby= module Sugoi class Application < Rails::Application config.load_defaults 6.1 config.generators do |g| g.factory_bot false end end end ``` lib/tasks/products.rake 做一個假資料指令 ```ruby= namespace :items do desc "Generate fake products" task :fake => :environment do 50.times do |i| product = FactoryBot.create(:product) puts "create product: #{i + 1} - #{product.name}" end puts "done!" end end ``` test/factories/products.rb 使用faker套件做假資料 ```ruby= FactoryBot.define do factory :product do name { Faker::Name.name } price { Faker::Number.within(range: 100..1000) } quantity { 1 } describtion { Faker::Lorem.paragraph(sentence_count: 4) } category { "MyString" } material { "MyString" } manufacturing_method { "MyString" } country { "MyString" } content { "MyText" } end end ```