RSpec: Moving to Request Specs from Controller Specs

Mintbit always keeps an eye on changelogs from Ruby, Rails and many commonly used gems, and tries to follow the recommendations and avoid deprecations.

One of the gems that Mintbit uses in every application is RSpec. This gem is widely used to test Rails applications and is constantly being updated. In the 3.5 release, request specs are recommended instead of controller specs for these reasons:

Here is a look at complete CRUD testing of a controller like PostsController.

We will be doing stuff in spec/requests/posts_spec.rb

  1. POST request for the create method.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
describe '#create' do
  before do
    sign_in user
  end

  context 'valid params' do
    before do
      post "/posts/", :params => {post: {name: "My Post",
                                         body: 'This is body'} }
    end

    it { expect(response).to have_http_status(302) }
    it { expect(Post.count).to eql 1 }
  end
end
  1. GET request for index method.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
describe '#index' do
  before do
    sign_in user
  end

  context 'valid params' do
    before do
      get "/posts/"
    end

    it { expect(response).to have_http_status(200) }
    it { expect(response).to render_template(:index) }
  end
end
  1. PUT request for update method.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
describe '#update' do
  before do
    sign_in user
  end

  context 'valid params' do
    before do
      put "/posts/#{post.id}", :params => {post: {title: "My Updated Title"}}
    end

    it { expect(response).to have_http_status(302) }
    it { expect(post.reload.title).to eql("My Updated Title") }
  end
end
  1. DELETE request for destroy method.
1
2
3
4
5
6
7
8
9
10
11
12
13
describe '#destroy' do
  before do
    sign_in user
  end

  context 'valid params' do
    before do
      delete "/posts/#{post.id}"
    end

    it { expect(Post.count).to eql 0 }
  end
end