我有gem devise
并且gem apartment
我正在使用它为每个设计的用户帐户创建单独的模式。
Apartment在该问题中的文档和建议建议使用 Rack 中间件在租户之间切换。在那种情况下,这是不可能的(据我所知),因为我依赖于用户而不是依赖于请求。
除了我的 RSpec 测试外,一切都很好。问题是在每个测试数据库都没有正确清理之后(它不会为新创建的用户删除架构)。如果我运行一小部分测试,所有测试都会通过,但如果我运行很多而不是Faker::Internet.first_name
生成已经被使用的用户名(这是无效的)。
所以这就是我的做法:
应用程序/控制器/application_controller.rb
def scope_tenant
Apartment::Database.switch(current_user.username)
end
app/controllers/albums_controller.rb(专辑模型belong_to :user
)
class AlbumsController < ApplicationController
before_action :authenticate_user! # devise magic
before_action :scope_tenant
应用程序/模型/用户.rb
after_create :create_schema
private
def create_schema
Apartment::Database.create(self.username)
end
这是我在规范中添加的内容:
规格/工厂/user.rb
FactoryGirl.define do
factory :user do
username { Faker::Name.first_name }
email { Faker::Internet.email("#{username}") }
password "login_as will not use it anyway"
end
end
规范/支持/auth_helpers.rb
Warden.test_mode!
def login_and_switch_schema(user)
login_as(user)
Apartment::Database.switch(user.username) # for some reason `login_as()` didn't do that by itself
end
规格/功能/albums_spec.rb
feature "Album Pages" do
given(:user) { create(:user) }
given(:album) { create(:album) }
around :each do
login_and_switch_schema user
end
scenario...
因为我有一些测试js: true
比我有:
规范/支持/database_cleaner.rb
RSpec.configure do |config|
config.before(:suite) do
DatabaseCleaner.clean_with(:truncation)
end
config.before(:each) do
DatabaseCleaner.strategy = :transaction
end
config.before(:each, js: true) do
DatabaseCleaner.strategy = :truncation
end
config.before(:each) do
DatabaseCleaner.start
end
config.after(:each) do
DatabaseCleaner.clean
end
end
所有来源的当前提交都可以在我的 github 上找到。
所以..主要问题是:如何在测试后为每个用户清理数据库创建的模式?我也会感谢任何其他评论。提前感谢您的帮助。