How to change subdomain in requests test with Rspec (for API testing)

rspec, ruby, ruby-on-rails

Solution

You can create a helper method in the `spec_helper.rb`, something like:

def my_get path, *args
  get "http://api.localhost.dev/#{path}", *args
end

And its usage will be:

require 'spec_helper'

describe "Garages" do

  describe "index" do
    it "should return status 200" do
      my_get 'garages'
      response.status.should be(200)
      response.body.should_not be_empty
    end
  end
end

Problem

I have a question which is really specific. I don't want to do a controller test but a requests test. And I don't want to use Capybara because I don't want to test user interaction but only response statuses. I have the following test under spec/requests/api/garage_spec.rb ``` require 'spec_helper' describe "Garages" do describe "index" do it "should return status 200" do get 'http://api.localhost.dev/garages' response.status.should be(200) response.body.should_not be_empty end end end ``` This works. But as I have to do more tests.. is there any way to avoid to repeat this? `http://api.localhost.dev` I tried with `setup { host! 'api.localhost.dev' }` But it doesn't do anything. A `before(:each)` block setting `@request.host` to something, of course crashes because `@request` is nil before performing any http request. The routes are set correctly (and in fact they work) in this way ``` namespace :api, path: '/', constraints: { subdomain: 'api' } do resources :garages, only: :index end ```

Original source