influitive / apartment

Database multi-tenancy for Rack (and Rails) applications
2.66k stars 460 forks source link

write RSpec tests for APIs #656

Open hdkhosravian opened 4 years ago

hdkhosravian commented 4 years ago

Hello I added the apartment gem to my project, and everything is working well in my development, and I haven't any problem. Right now, I want to update my RSpec tests with tenant subdomains. I added: Apartment::Elevators::Subdomain.excluded_subdomains = ['www'] Also, for RSpec, I added:


RSpec.configure do |config|
  config.before(:suite) do
    # Clean all tables to start
    DatabaseCleaner.clean_with :truncation
    # Use transactions for tests
    DatabaseCleaner.strategy = :transaction
    # Truncating doesn't drop schemas, ensure we're clean here, app *may not* exist
    Apartment::Tenant.drop('test_app') rescue nil
    # Create the default tenant for our tests
    Apartment::Tenant.create('test_app')
  end

  config.before(:each) do
    # Start transaction for this test
    DatabaseCleaner.start
    # Switch into the default tenant
    Apartment::Tenant.switch! 'test_app'
  end

  config.after(:each) do
    # Reset tentant back to `public`
    Apartment::Tenant.reset
    # Rollback transaction
    DatabaseCleaner.clean
  end
end

My Test is:


RSpec.describe Api::V1::AccountsController, type: :request do
  describe '.create' do
    context 'valid requests' do
      it 'creates accounts' do
        # Require data
        user   = create(:user)
        project   = create(:project, user: user)

        attributes = {
          account: FactoryBot.attributes_for(:account_params),
        }

        # Request
        sign_in(user)

        post "/en/api/v1/projects/#{project.id}/accounts",
             headers: auth_header,
             params: attributes

        # Expects
        # MY TESTS ARE HERE
      end
    end
  end
end

right now, I haven't any subdomain as default, so If I update the host like this host! "test_app.example.com" and call my API like this: post "/en/api/v1/projects/#{project.id}/accounts" I'm getting this error *** URI::InvalidURIError Exception: the scheme http does not accept registry part: test_app.example.com (or bad hostname?) and if I send the request like this: post "en/api/v1/projects/#{project.id}/accounts" I'll get this error: *** URI::InvalidURIError Exception: bad URI(is not URI?): "http://test_app.example.com:80en/api/v1/projects/1/accounts"

Does anybody know how I can fix this issue and send my request to the correct subdomain? (this API working well in my development)

hdkhosravian commented 4 years ago

There is nobody to have this issue before?