Setting host! in before (:each or :all) does not work in Request-specs
Closed this issue · 3 comments
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
endThe 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.
To clarify, what are you expecting to work here which isn't, the host! functionality is part of the Rails test helpers which sets the header HTTP_HOST for a test request that makes Rails act as if that domain name was used, but it doesn't affect the IP address any server is listening on, or a request is made from...
Ah, I see! So whatever I do, it won't call a remote endpoint, except if I use rest-client or some other library explicitly, correct?
Kind regards and thank you for the clarification! I missed that point explicitly mentioned and was expecting a different behavior.
Indeed, there is no built in functionality for testing remote systems.