Skip to content

Setting host! in before (:each or :all) does not work in Request-specs #2813

@steviee

Description

@steviee

What Ruby, Rails and RSpec versions are you using?

Ruby version: 3.3.6
Rails version: 8.0.0
RSpec version: 3.13

  • rspec-core 3.13.2
  • rspec-expectations 3.13.3
  • rspec-mocks 3.13.2
  • rspec-rails 7.1.0
  • rspec-support 3.13.1

Observed behaviour

I prepared this spec

require 'rails_helper'

# This spec is a basic test that verifies that the code is working.
RSpec.describe 'Basic API Tests' do
  describe 'GET /api/users/steviee/repos', type: :request do
    before :each do
      host! 'timeapi.io'
    end

    it 'returns successful response' do
      get "/api/time/current/zone?timeZone=Europe/Berlin"
      expect(response).to have_http_status(200)
      expect(response.body["timeZone"]).to eq('Europe/Berlin')
    end
  end
end

The above code is expected to run the request against the host timeapi.io, however it is run against 127.0.0.1 as per logs:

[c93d8682-67ca-4aad-9545-5705a736ee01] Started GET "/api/time/current/zone?timeZone=Europe/Berlin" for 127.0.0.1 at 2024-11-12 16:17:57 +0100
[c93d8682-67ca-4aad-9545-5705a736ee01]   
[c93d8682-67ca-4aad-9545-5705a736ee01] ActionController::RoutingError (No route matches [GET] "/api/time/current/zone"):
[c93d8682-67ca-4aad-9545-5705a736ee01]   
  TRANSACTION (0.0ms)  ROLLBACK TRANSACTION
F

Failures:

  1) Basic API Tests GET /api/users/steviee/repos returns successful response
     Failure/Error: expect(response).to have_http_status(200)
       expected the response to have status code 200 but it was 404
     # ./spec/accounts/basic_api_spec.rb:11:in `block (3 levels) in <top (required)>'

Finished in 0.22201 seconds (files took 0.5135 seconds to load)
1 example, 1 failure

Failed examples:

rspec ./spec/accounts/basic_api_spec.rb:9 # Basic API Tests GET /api/users/steviee/repos returns successful response

Expected behaviour

The expected behavior would be calling another host as per host!-setting.

Can you provide an example reproduction?

See above.

Created a new fress api-only Rails 8.0.0 app, added RSpec and the spec from above.
No further configuration on RSpec was done.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions