Ruby on Rails Testing with RSpec Requests

Kayla
3 min readOct 21, 2021
RSpec
rspec.info

Hello! Here’s a tutorial on how to set up a simple RSpec test for a Ruby on Rails app. The test is related to user signup functionality and tests for the ability to create a new user. The test will use a request spec, requesting a JSON response. The expected result of the test will include an HTTP status of 201 Created. You can customize the test based on your own parameters.

To get started:

1. Add the following gem to your development group and then run bundle to install:

gem ‘rspec-rails’, ‘~> 4.0.1’

2. Set up your project to use RSpec by running:

rails generate rspec:install

This creates an rspec file which requires the spec_helper and it also creates a spec directory including the spec_helper itself. Should also have a rails_helper.

3. Create a new controller which will automatically create the spec file under the spec directory:

rails g controller Users

If you already have a controller created, you can create a folder under the spec directory called ‘requests.’ Then create a file within ‘requests’ using the naming convention shown below.

You should end up with the following request spec if you created a Users controller:

4. Update your describe block if needed

You can use RSpec.describe to reference strings or classes. I’m going to update this to “Create Users” because I’ll eventually want to have sections for each method. Describe blocks can be used to organize your tests.

5. Next, add an it block to describe the expected behavior / outcome of the test. For example:

it ‘returns created status after creating a new user’ do

6. For this test, we’re going to be requesting a JSON response, so we’ll need to include headers.

7. Now we can add the request and body

My controller requires username, password and avatar as parameters when creating a new user, so I can add the following:

8. Finally, we’ll need to add an assertion.

In this example, we’ll confirm that the JSON response includes an HTTP status of 201 Created.

9. That’s it! Run rspec in your terminal and see if it passes!

If it doesn’t pass, then you can re-run this test as you build/debug your signup functionality.

Other tests that would be helpful for signup functionality:

context "with valid user params" do
let!(:user_params) { { name: 'Bob', email: '' } }
it 'creates a new user' doexpect { post ‘/users’, params: user_params }.to change(User, :count).by(1)
end
it 'returns the user data' dopost '/users', params: user_params
expect(response.body).to include_json({
id: a_kind_of(Integer),
username: ‘’,
avatar: ‘’
})
end
end

--

--