#103 Sample Data with Factory Bot and Faker
10/29/2017

Summary

Factory Bot is a fixtures replacement which can generate the needed records directly in the tests. Faker can be used to create fake data for these records.
4
ruby rails test 8:07 min

Summary

Gemfilegroup :test do
  # gem 'factory_bot'
  gem 'factory_bot_rails'
  gem 'faker'
end
rails_helper.rb# require 'support/factory_bot'
Dir[Rails.root.join('spec/support/**/*.rb')].each { |f| require f }
spec/factories/users.rbFactoryBot.define do
  factory :user do
    first_name 'John'
    last_name 'Doe'
    email '[email protected]'
    active true
  end

  factory :random_user, class: User do
    first_name { Faker::Name.first_name }
    last_name { Faker::Name.last_name }
    email { Faker::Internet.safe_email }
    active true
  end
end
user_spec.rbFactoryBot.define do
  factory :user do
    first_name 'John'
    last_name 'Doe'
    email '[email protected]'
    active true
  end

  factory :random_user, class: User do
    first_name { Faker::Name.first_name }
    last_name { Faker::Name.last_name }
    email { Faker::Internet.safe_email }
    active true
  end
end
user.rbclass User < ApplicationRecord
  scope :active_users, -> { where(active: true) }
  scope :inactive_users, -> { where(active: false) }
  validates :first_name, presence: true
  validates :last_name, presence: true
  validates :email, presence: true, uniqueness: true
end