๐ŸŒ

Request Specs

Integration tests for HTTP request/response

Request Spec is an integration test that replaces Controller tests. It simulates real HTTP requests to test the entire stack from routing to response.

RSpec.describe 'Posts', type: :request do
  let(:user) { create(:user) }
  let(:post_record) { create(:post, user: user) }

  describe 'GET /posts' do
    it 'returns the list' do
      get posts_path
      expect(response).to have_http_status(:success)
    end
  end

  describe 'POST /posts' do
    context 'when logged in' do
      before { sign_in user }  # Devise helper

      it 'creates a new post' do
        expect {
          post posts_path, params: { post: { title: 'Title', content: 'Content' } }
        }.to change(Post, :count).by(1)

        expect(response).to redirect_to(post_path(Post.last))
      end
    end

    context 'when not logged in' do
      it 'redirects to login page' do
        post posts_path, params: { post: { title: 'Title' } }
        expect(response).to redirect_to(new_user_session_path)
      end
    end
  end
end

Key Points

1

Create spec files in spec/requests/ directory

2

Simulate HTTP requests with get/post/patch/delete methods

3

Pass request parameters with params: option

4

Set request headers with headers: option (Turbo Stream, etc.)

5

expect(response).to have_http_status(:success) โ€” status code verification

6

expect { action }.to change(Model, :count) โ€” data change verification

Pros

  • Real HTTP request simulation โ€” realistic tests
  • Full stack verification from routing to response
  • Controller + View integration test
  • Test interaction with middleware like Devise

Cons

  • Slower than unit tests
  • Root cause tracking can be complex on failure
  • Test time increases with view rendering
  • Not suitable for fine-grained Controller logic testing

Use Cases

CRUD endpoint tests Authentication/authorization tests Turbo Stream response tests API response verification