Rails new app with API version

rails new app_name --api -T
# --api define api only application and -T to drop Mini Tests (we'll use RSpec instead)

Testing

We will use Rspec, FactoryBot, ShouldMatchers, Database Cleaner, Faker

Setup the gemfile like so:

# Gemfile
gem 'rails', '~> 6.0.0'
# Use postgresql as the database for Active Record
gem 'pg', '>= 0.18', '< 2.0'
# Use Puma as the app server
gem 'puma', '~> 3.11'
# Use Redis adapter to run Action Cable in production
# gem 'redis', '~> 4.0'
# Use Active Model has_secure_password
gem 'bcrypt', '~> 3.1.7'

# Reduces boot times through caching; required in config/boot.rb
gem 'bootsnap', '>= 1.4.2', require: false

# Use Rack CORS for handling Cross-Origin Resource Sharing (CORS), making cross-origin AJAX possible
gem 'rack-cors'

group :development, :test do
  # Call 'byebug' anywhere in the code to stop execution and get a debugger console
  gem 'byebug', platforms: [:mri, :mingw, :x64_mingw]
  gem 'rspec-rails', '~> 3.5'
  gem 'dotenv-rails'
  gem 'rb-readline'
end

group :development do
  gem 'listen', '>= 3.0.5', '< 3.2'
  # Spring speeds up development by keeping your application running in the background. Read more: <https://github.com/rails/spring>
  gem 'spring'
  gem 'spring-watcher-listen', '~> 2.0.0'
  gem 'factory_bot_rails', '~> 4.0'
  gem 'shoulda-matchers', '~> 3.1'
  gem 'faker'
  gem 'database_cleaner'
end

# Windows does not include zoneinfo files, so bundle the tzinfo-data gem
gem 'tzinfo-data', platforms: [:mingw, :mswin, :x64_mingw, :jruby]

Initialise the spec directory

rails generate rspec:install

You might need to setup postgres before setting up the spec directory (in my case I had an error when trying to setup the directory and didn't have default sqlite configured).

gem 'pg'
gem 'rails_12factor', group: :production

Setup the file telling Rails to use Postgres instead of Sqlite:

default: &default
  adapter: postgresql
  encoding: unicode
  username: <%= ENV['POSTGRES_USER'] %>
  password: <%= ENV['POSTGRES_PASSWORD'] %>
  pool: 5
  timeout: 5000
  host: <%= ENV['POSTGRES_HOST'] %>
development:
  <<: *default
  database: <%= ENV['POSTGRES_DB'] %>
	username: <%= ENV['POSTGRES_USER'] %>
	password: <%= ENV['POSTGRES_PASSWORD'] %>
test:
  <<: *default
  database: <%= ENV['POSTGRES_TEST_DB'] %>
production:
  <<: *default
  database: <%= ENV['POSTGRES_DB'] %>

To mange env variable we use a gem called dotenv-rails

gem 'dotenv-rails'

Now create a .env file in our dev env with the following params:

POSTGRES_USER=''
POSTGRES_PASSWORD=''
POSTGRES_HOST='localhost'
POSTGRES_DB='your_database_name'
POSTGRES_TEST_DB='your_database_name_test'

If we run the configuration for tests will work now:

rails generate rspec:install

Create a factories directory: