#103 Sample Data with Factory Bot and Faker

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.
ruby rails test 8:07

Resources

Summary

# Gemfile
group :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.rb
FactoryBot.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.rb
FactoryBot.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.rb
class 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