I have a rails application which acts differently depending on what domain it\'s accessed at (for example www.myapp.com will invoke differently to user.myapp.com). In produc
I believe you can modify the HTTP_HOST
or SERVER_NAME
environment vars to change the request that goes to the router:
ENV['SERVER_NAME'] = "user.myapp.com"
See raw_host_with_port
in actionpack/lib/action_controller/request.rb.
In Feature specs, host! has been deprecated. Add these to your spec_helper.rb
:
# Configure Capybara expected host
Capybara.app_host = "http://test.domain"
# Configure actual routes host during test
before(:each) do
default_url_options[:host] = <myhost>
end
In Request specs, keep using host! :
host! "test.domain"
Alternatively refactor it in before(:each)
blocks, or configure it globally for request specs at spec_helper.rb
level:
RSpec.configure do |config|
config.before(:each, type: :request) do
host! "test.domain"
end
end
For Rspec Request specs, use before(:each) { host! 'example.com' }
See more at: https://relishapp.com/rspec/rspec-rails/v/3-6/docs/request-specs/request-spec https://github.com/rspec/rspec-rails/issues/1662#issuecomment-241201056
I think all answers are incomplete here... To enumerate all possible cases:
Integration Specs (inheriting from ActionDispatch::IntegrationTest
):
host! "my.awesome.host"
See the docs, section 5.1 Helpers Available for Integration Tests.
Controller Specs (inheriting from ActionController::TestCase
)
@request.host = 'my.awesome.host'
See the docs, section 4.4 Instance Variables Available.
Feature Specs (through Capybara)
Capybara.default_host = "http://my.awesome.host"
# Or to configure domain for route helpers:
default_url_options[:host] = "my.awesome.host"
From @AminAriana's answer
View Specs (inheriting from ActionView::TestCase
)
@request.host = 'my.awesome.host'
...or through RSpec:
controller.request.host = "my.awesome.host"
See the rspec-rails
view spec docs.
Yet another answer:
request.host = "user.myapp.com"
I know it resembles the correct answer, but please bear with me. I don't like assignment operation in test just to set things up, I'd prefer an explicit stub. Interestingly, stubbing like this won't work:
allow(request).to receive(:host).and_return("user.myapp.com")
I personally prefer stubbing over assignment, that way I get 2 benefit, one is that it will be validated by rspec's verify double, second is that it is explicitly saying that is a stub, not part of the test excercise.
@request.host = 'user.myapp.com'
is not right.
should use host!('user.myapp.com')