Adam Grzybowski

Programming

Handling subdomains in RSpec

jcapt
before { host! "api.example.com" }

host! the method allows controlling host sent in RSpec tests.

Adding it to RSpec

# spec/support/subdomain_helpers.rb
module SubdomainHelper
  def within_subdomain(subdomain)
    before { host! "#{subdomain}.server.local" }
    after  { host! "www.server.local" }
    yield
  end
end

# spec/rails_spec.rb
config.extend SubdomainHelper, type: :request

Then using it in RSpec tests

RSpec.describe "API call", type: :request do
  within_subdomain :api do
    describe "method" do
      it "checks request host" do
        get api_path

        expect(response.host).to eq("api.server.local")
      end
    end
  end
end

Tags:
Back to top