Setting up Rails 6 API and RSpec Test Environment

Ali Erbay
4 min readAug 14, 2020

Thanks to Rails developers, setting up a Rails application is easy but having it to include custom RSpec test environment requires some custom manual work. In this article, I will try to show how I set up my application ready for further development.

With the advent of client-side frameworks such as React, Vue, and Angular, more developers are using Rails to build a back-end that is shared between their web application and other native applications. Many developers are treating their web application as just an API client delivered as HTML with Javascript or Typescript that consumes a JSON API.

Setup Rails API

This is going to be an API only application so we don’t need some of the helpers of a default Rails application.

>rails new your_application --api --skip-test

Running the terminal command above will setup your bare Rails API app,

rails new your_application will create your_application folder and setup Rails app inside that folder

--api option will accomplish three things;

  • Configure your application to start with a more limited set of middleware than normal. Specifically, it will not include any middleware primarily useful for browser applications (like cookies support) by default.
  • Make ApplicationController inherit from ActionController::API instead of ActionController::Base. As with middleware, this will leave out any Action Controller modules that provide functionalities primarily used by browser applications.
  • Configure the generators to skip generating views, helpers, and assets when you generate a new resource.

One of the many cool things about all Rails apps is that whenever you create a Rails app, Rails also creates a test directory within the app. Minitest is the default testing library used by Rails. But I prefer to use RSpec because it has great documentation.

--skip-test option will skip configuration for the default Minitest testing tool and its additional folders and test files.

Rails come with built-in support for SQLite, which is a lightweight serverless database application. While a busy production environment may overload SQLite, it works well for development and testing. Rails default to using an SQLite database when creating a new project, but you can always change it later. Especially if you want to deploy your project to Heroku, you need to use PostgreSQL. By using --database=postgresql option when starting up a project, it will automatically set the project’s database to PostgreSQL in the config/database.yml file.

While we are at it, run rails db:create on your terminal to get your database ready for further development.

Debugging Tools

I like using Pry as runtime developer console for Rails so I add gem package called pry-rails to the Gemfile in addition to that to boost its debugging potential I also add the pry-byebug gem. It adds next, step, finish, continueand breakcommands to pry using byebug.

Gemfile should look like this for now;

Before running bundlecommand(yes, I use bundler package manager as you should also use), there is one more issue we need to deal with. We need to enable CORS in our application.

Enable CORS

Cross-Origin Resource Sharing (CORS) is a mechanism that uses additional HTTP headers to tell a browser to let a web application running at one origin (domain) have permission to access selected resources from a server at a different origin. A web application executes a cross-origin HTTP request when it requests a resource that has a different origin (domain, protocol, and port) than its own origin.

Add the following line at the end of your Gemfile;

gem 'rack-cors', require: 'rack/cors'

Run bundle on your terminal,

Then, you need the following configuration to config/application.rb file

Setup Test Tools

Now we can start setting up the test environment, for this we need to add three gem packages named; rspec-rails, shoulda-matchers, factory_bot_rails.

Then run bundle on the terminal, right after the bundler did its job go ahead and install RSpec for your project

> rails generate rspec:install

This will create /spec folder and configuration files.

Shoulda-matchers package offers useful functionality such as over 30 pre-defined matchers, short one-liner test codes, and clear/actionable messages. Now we must tell the gem which test framework we are using and which portion of the matchers we want to use. This can be done by supplying a configuration block in spec/rails_helper.rb

You can also create a support file spec/support/your_support_file.rb and add configuration blocks if you don’t wish to keep your rails_helper.rb file crowded. But you need to require that support file in spec/rails_helper.rb

We will need to stub in some data and model instances in order to run our tests effectively. factory_bot is a fixtures replacement with a straightforward definition syntax, support for multiple build strategies (saved instances, unsaved instances, attribute hashes, and stubbed objects), and support for multiple factories for the same class (user, admin_user, and so on), including factory inheritance. An addition to the configuration in spec/rails_helper.rbfile is needed for Factory Bot to run in our test files;

One more adjustment left that will make our test outputs easy to understand and read. We should change .rspec file located at the root folder;

--color will enable color in the test output (may not be needed in newer versions) and --format documentation will print out every test failure/success message in the terminal output.

That’s all for the setup! Now you can stub your database models with Factory Bot and write readable test codes with shoulda-matchers assertions for your Rails API unit and controller/request specs!

--

--

Ali Erbay

Full Stack Developer BDD/TDD || Ruby on Rails || React || React Native || NodeJS || Express https://github.com/kermit-klein