RSpec - FactoryBot - DatabaseCleaner

Configure RSpec, FactoryBot and DatabaseCleaner in a brand new Rails project.
Icons/chart bar
Used 95 times
Created by
A Alex Ventura

Usage

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

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

Review the code before running this template on your machine.

def do_bundle
  # Custom bundle command ensures dependencies are correctly installed
  Bundler.with_unbundled_env { run "bundle install" }
end

# Test suite
gem_group :development, :test do
  gem "rspec-rails"
  gem 'factory_bot_rails'
  gem 'shoulda-matchers'
  gem 'database_cleaner-active_record'
  gem 'standard'
  # 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

# shoulda-matchers
file 'spec/support/shoulda_matchers.rb', <<-CODE
Shoulda::Matchers.configure do |config|
  config.integrate do |with|
    with.test_framework :rspec
    with.library :rails
  end
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

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

Sign up or Login to leave a comment.