#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.
10
ruby
rails
test
8:07
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.
10
Resources
Factory Bot Gem - https://github.com/thoughtbot/factory_bot
Factory Bot Getting Starting - https://github.com/thoughtbot/factory_bot/blob/master/GETTING_STARTED.md
Faker Gem - https://github.com/stympy/faker
Source - https://github.com/driftingruby/103-sample-data-with-factory-bot-and-faker
Summary
Gemfilegroup :test do
# gem 'factory_bot'
gem 'factory_bot_rails'
gem 'faker'
endrails_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
enduser_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
enduser.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