Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I change the default "www.example.com" domain for testing in rails?

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 production use this all works fine but my test code always sees a hostname of "www.example.com".

Is there a clean way of having a test specify the hostname it's pretending to access?

like image 840
Denis Hennessy Avatar asked Mar 01 '09 00:03

Denis Hennessy


3 Answers

  • Integration/Request Specs (inheriting from ActionDispatch::IntegrationTest):

     host! 'my.awesome.host'
    

See the docs, section 5.1 Helpers Available for Integration Tests.

alternatively, configure it globally for request specs at spec_helper.rb level:

RSpec.configure do |config|
  config.before(:each, type: :request) do
    host! 'my.awesome.host'
  end
end
  • 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.

like image 185
deivid Avatar answered Nov 19 '22 01:11

deivid


@request.host = 'user.myapp.com'
like image 35
jcrossley3 Avatar answered Nov 19 '22 01:11

jcrossley3


Feature specs

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

Request specs

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
like image 29
Amin Ariana Avatar answered Nov 19 '22 00:11

Amin Ariana