rspec / rspec-rails

RSpec for Rails 6+
https://rspec.info
MIT License
5.19k stars 1.04k forks source link

Support `have_http_status` with `Rack::MockResponse` #2771

Closed cbliard closed 5 months ago

cbliard commented 5 months ago

When using rack-test, doing something like expect(last_response).to have_http_status(:ok) would fail with the error "expected a response object, but an instance of Rack::MockResponse was received".

This PR creates a ActionDispatch::TestResponse from the Rack::MockResponse to make have_http_status usable in specs relying on rack-test to perform requests.

It should fix rubocop/rubocop-rspec_rails#20.

Reproduction script:

# frozen_string_literal: true

require "bundler/inline"

gemfile(true) do
  source "https://rubygems.org"

  git_source(:github) { |repo| "https://github.com/#{repo}.git" }

  # Activate the gem you are reporting the issue against.
  gem "rails", "6.1.0"
  gem "rspec-rails"
end

require "rspec-rails"
require "action_controller/railtie"

class TestApp < Rails::Application
  config.root = __dir__
  config.hosts << "example.org"
  config.session_store :cookie_store, key: "cookie_store_key"
  secrets.secret_key_base = "secret_key_base"

  config.logger = Logger.new($stdout)
  Rails.logger  = config.logger

  routes.draw do
    get "/" => "test#index"
  end
end

class TestController < ActionController::Base
  include Rails.application.routes.url_helpers

  def index
    render plain: "Hello, World!"
  end
end

require "rspec/autorun"
require "rspec/rails/matchers"

RSpec.describe "additions", type: :request do
  include Rack::Test::Methods
  include RSpec::Rails::Matchers

  it do
    get "/"
    expect(last_response).to have_http_status(:ok)
  end

  private

  def app
    Rails.application
  end
end
cbliard commented 5 months ago

Can you please provide a reproduction script a-la #2502 (comment) ?

I added one in the description. Thanks for pointing to a nice example.

cbliard commented 5 months ago

Thanks @pirj and @JonRowe for your reviews and suggestions. I just pushed a fix.

JonRowe commented 5 months ago

Thanks!

JonRowe commented 3 months ago

Released in 6.1.4