RSpec - FactoryBot - DatabaseCleaner

Ruby on Rails XP KIT
Icons/chart bar
Used 24 times
Created by
P Positive Nature Creative

Usage
Starter Kit: XP BDD TDD

Dependencies:
  • rspec-rails
  • simplecov
  • factory_bot_rails
  • database_cleaner-active_record
  • rubocop-rails
  • rubycritic
  • pry-byebug

TODO:
  • dependabot vs renovate
  • CI/CD setup
  • Design System Style Guide

Run this command in your Rails app directory in the terminal:

rails app:template LOCATION="https://railsbytes.com/script/Xo5s7N"
Template Source

Review the code before running this template on your machine.

def do_bundle
  # bundler 2.1
  # Custom bundle command ensures dependencies are correctly installed
  # with_clean_env is deprecated, it changed to with_unbundled_env
  # https://github.com/rubygems/bundler/blob/master/lib/bundler.rb#L337
  # https://github.com/rubygems/bundler/blob/2-1-stable/lib/bundler.rb#L368
  # source: https://github.com/thoughtbot/suspenders/issues/1047
  # https://bundler.io/man/bundle-exec.1.html
  # https://bundler.io/compatibility
  Bundler.with_unbundled_env { run "bundle install" }
  
  # bundler 2.0.2
  # NoMethodError with_unbundled_env
  # https://github.com/rubygems/bundler/blob/2-0-stable/lib/bundler.rb#L286
  # Bundler.with_clean_env { run "bundle install" }
  # SOLUTION: `gem update bundler`
  # https://stackoverflow.com/questions/1628563/move-the-most-recent-commits-to-a-new-branch-with-git
end

## Test suite
gem_group :development, :test do
  gem "rspec-rails"
  gem 'simplecov'
  gem 'factory_bot_rails'
  gem 'database_cleaner-active_record'
  # gem 'standard'
  gem "rubocop-rails", require: false
  # gem 'rubocop-rspec', require: false
  gem "rubycritic", require: false
  # To debug bit better with breakpoints¬
  gem 'pry-byebug'
end

# run "bundle install"
do_bundle
rails_command "generate rspec:install"

# factory_bot_rails
file 'spec/support/factory_bot.rb', <<-CODE
RSpec.configure do |config|
  config.include FactoryBot::Syntax::Methods
end
CODE


# database_cleaner-active_record
file 'spec/support/database_cleaner.rb', <<-CODE
RSpec.configure do |config|
  config.before(:suite) do
    DatabaseCleaner.strategy = :transaction
    DatabaseCleaner.clean_with(:truncation)
  end

  config.around(:each) do |example|
    DatabaseCleaner.cleaning do
      example.run
    end
  end
end
CODE

# Rubocop extensions
file '.rubocop.yml', <<-CODE
require:
#  - rubocop-rspec
  - rubocop-rails
CODE

# require config files
inject_into_file "spec/rails_helper.rb", after: "require 'rspec/rails'" do
  <<~EOF
  
  require 'support/factory_bot'
  require 'support/database_cleaner'
  EOF
end

inject_into_file "spec/spec_helper.rb", before: "RSpec.configure" do
  <<~EOF
  require 'simplecov'
  SimpleCov.start 'rails'
  EOF
end
Comments

Sign up or Login to leave a comment.