首页 > 解决方案 > 使用公寓 gem 为 API 编写 RSpec 测试

问题描述

我将公寓 gem 添加到我的项目中,并且在我的开发中一切正常,我没有任何问题。现在,我想用租户子域更新我的 RSpec 测试。我补充说: Apartment::Elevators::Subdomain.excluded_subdomains = ['www'] 另外,对于 RSpec,我补充说:


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

我的测试是:


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

现在,我没有任何默认子域,所以如果我像这样更新主机host! "test_app.example.com"并像这样调用我的 API: post "/en/api/v1/projects/#{project.id}/accounts"我收到此错误*** URI::InvalidURIError Exception: the scheme http does not accept registry part: test_app.example.com (or bad hostname?) ,如果我发送这样的请求:post "en/api/v1/projects/#{project.id}/accounts"我将收到此错误:*** URI::InvalidURIError Exception: bad URI(is not URI?): "http://test_app.example.com:80en/api/v1/projects/1/accounts"

有谁知道我如何解决这个问题并将我的请求发送到正确的子域?(这个 API 在我的开发中运行良好)

标签: ruby-on-railsrubyrspecmulti-tenantapartment-gem

解决方案


推荐阅读