Setting up Rspec testing for Rails 5

Zack Yap
Back to Rails
Published in
2 min readMar 25, 2017

Setting things up always seem to take different paths for different people. Here’s the steps I took to get it right for Rails 5. I’m mostly following along EverydayRails’ guide to testing here, but I had to troubleshoot and do some things differently.

Gemfile

First things first, let’s get the required Gems.

Of course, let’s install the bundle.

$ bundle

Database.yml

As I’m using postgresql as my database, this is what my database.yml looks like. Remember to replace myapp with whatever your app’s name is.

This is what the top portion of my database.yml looks like.

Make sure the database has been created and to do migrations on the test database.

$ rake db:create:all
$ rake db:migrate RAILS_ENV=test

Rspec Installation and Configuration

Let’s install Rspec

$ rails g rspec:install
create .rspec
create spec
create spec/spec_helper.rb
create spec/rails_helper.rb

And then we add Capybara support to Rspec. Add this to your newly created spec/spec_help.rb

require "capybara/rspec"

Generators

I followed exactly as recommended by EverydayRails in this part, adding this to config/application.rb

Here’s the step by step explanation:

Can you guess what this code is doing? Here’s a rundown:

:fixtures => true specifies to generate a fixture for each model (using a Factory Girl factory, instead of an actual fixture)

:view_specs => false says to skip generating view specs. I won’t cover them in this book; instead we’ll use request specs to test interface elements.

:helper_specs => false skips generating specs for the helper files Rails generates with each controller. As your comfort level with RSpec improves, consider changing this option to true and testing these files.

:routing_specs => false omits a spec file for your config/routes.rb file. If your application is simple, as the one in this book will be, you’re probably safe skipping these specs. As your application grows, however, and takes on more complex routing, it’s a good idea to incorporate routing specs.

And finally, g.fixture_replacement :factory_girl tells Rails to generate factories instead of fixtures, and to save them in the spec/factories directory.

.rspec

I had to do this last step in order to get the test working. Add this to your .rpsec

--require rails_helper

There. We’re good to go to start writing tests for our app.

--

--

Zack Yap
Back to Rails

Product Manager @ Xfers, Writes in English, Ruby and JS.