我在做什么
我最近在Multitenancy with Scopes(需要订阅)作为指南之后实施了多租户(使用范围) 。注意:我正在使用可怕的“default_scope”来确定租户范围(如 Ryan 的 Railscast 中所示)。一切都在浏览器中运行良好,但我的许多(不是全部)测试都失败了,我不知道为什么。
我从头开始构建身份验证(基于此 Railscast:Authentication from Scratch(修订版) - 需要订阅)并使用 auth_token 实现“记住我”功能(基于此 Railscast:Remember Me & Reset Password)。
我的问题
为什么这个测试失败了,为什么这两种变通方法有效?我已经被难住了几天了,只是想不通。
我认为正在发生的事情
我正在调用 Jobs#create 操作,并且 Job.count减少1 而不是增加1。我认为正在发生的事情是正在创建工作,然后应用程序正在失去“租户”分配(租户正在下降为零),并且测试正在为错误的租户计算工作。
奇怪的是它期待“1”并得到“-1”(而不是“0”),这意味着它正在计数(请注意,在 before 块中已经创建了一个“种子”作业,所以它可能正在计数“ 1" 在调用 #create 之前),调用 create 操作(这应该将计数总共增加 1 到 2),然后失去租户并切换到有 0 个工作的 nil 租户。所以:
- 计数 1(种子工作)
- 创建工作
- 失去租户
- 在新(可能为零)租户中计算 0 个工作
...导致 Job.count 发生 -1 变化。
您可以在下面看到,我通过在测试中的 Job.count 行中添加“.unscoped”来半确认这一点。这意味着存在预期的工作数量,但这些工作不在应用程序正在测试的租户中。
我不明白的是它是如何失去租户的。
代码
我试图获取我的代码的相关部分,并且我创建了一个专用的单测试规范,以使其尽可能易于剖析。如果我可以做任何其他事情来简化可能的回答者,请告诉我该怎么做!
# application_controller.rb
class ApplicationController < ActionController::Base
protect_from_forgery
include SessionsHelper
around_filter :scope_current_tenant
private
def current_user
@current_user ||= User.unscoped.find_by_auth_token!(cookies[:auth_token]) if cookies[:auth_token]
end
helper_method :current_user
def current_tenant
@current_tenant ||= Tenant.find_by_id!(session[:tenant_id]) if session[:tenant_id]
end
helper_method :current_tenant
def update_current_tenant
Tenant.current_id = current_tenant.id if current_tenant
end
helper_method :set_current_tenant
def scope_current_tenant
update_current_tenant
yield
ensure
Tenant.current_id = nil
end
end
# sessions_controller.rb
class SessionsController < ApplicationController
def create
user = User.unscoped.authenticate(params[:session][:email], params[:session][:password])
if user && user.active? && user.active_tenants.any?
if params[:remember_me]
cookies.permanent[:auth_token] = user.auth_token
else
cookies[:auth_token] = user.auth_token
end
if !user.default_tenant_id.nil? && (default_tenant = Tenant.find(user.default_tenant_id)) && default_tenant.active
# The user has a default tenant set, and that tenant is active
session[:tenant_id] = default_tenant.id
else
# The user doesn't have a default
session[:tenant_id] = user.active_tenants.first.id
end
redirect_back_or root_path
else
flash.now[:error] = "Invalid email/password combination."
@title = "Sign in"
render 'new'
end
end
def destroy
cookies.delete(:auth_token)
session[:tenant_id] = nil
redirect_to root_path
end
end
# jobs_controller.rb
class JobsController < ApplicationController
before_filter :authenticate_admin
# POST /jobs
# POST /jobs.json
def create
@job = Job.new(params[:job])
@job.creator = current_user
respond_to do |format|
if @job.save
format.html { redirect_to @job, notice: 'Job successfully created.' }
format.json { render json: @job, status: :created, location: @job }
else
flash.now[:error] = 'There was a problem creating the Job.'
format.html { render action: "new" }
format.json { render json: @job.errors, status: :unprocessable_entity }
end
end
end
end
# job.rb
class Job < ActiveRecord::Base
has_ancestry
default_scope { where(tenant_id: Tenant.current_id) }
.
.
.
end
# sessions_helper.rb
module SessionsHelper
require 'bcrypt'
def authenticate_admin
deny_access unless admin_signed_in?
end
def deny_access
store_location
redirect_to signin_path, :notice => "Please sign in to access this page."
end
private
def store_location
session[:return_to] = request.fullpath
end
end
# spec_test_helper.rb
module SpecTestHelper
def test_sign_in(user)
request.cookies[:auth_token] = user.auth_token
session[:tenant_id] = user.default_tenant_id
current_user = user
@current_user = user
end
def current_tenant
@current_tenant ||= Tenant.find_by_id!(session[:tenant_id]) if session[:tenant_id]
end
end
# test_jobs_controller_spec.rb
require 'spec_helper'
describe JobsController do
before do
# This is all just setup to support requirements that the admin is an "Admin" (role)
# That there's a tenant for him to use
# That there are some workdays - a basic requirement for the app - jobs, checklist
# All of this is to satisfy assocations and
@role = FactoryGirl.create(:role)
@role.name = "Admin"
@role.save
@tenant1 = FactoryGirl.create(:tenant)
@tenant2 = FactoryGirl.create(:tenant)
@tenant3 = FactoryGirl.create(:tenant)
Tenant.current_id = @tenant1.id
@user = FactoryGirl.create(:user)
@workday1 = FactoryGirl.create(:workday)
@workday1.name = Time.now.to_date.strftime("%A")
@workday1.save
@checklist1 = FactoryGirl.create(:checklist)
@job = FactoryGirl.create(:job)
@checklist1.jobs << @job
@workday1.checklists << @checklist1
@admin1 = FactoryGirl.create(:user)
@admin1.tenants << @tenant1
@admin1.roles << @role
@admin1.default_tenant_id = @tenant1.id
@admin1.pin = ""
@admin1.save!
# This is above in the spec_test_helper.rb code
test_sign_in(@admin1)
end
describe "POST create" do
context "with valid attributes" do
it "creates a new job" do
expect{ # <-- This is line 33 that's mentioned in the failure below
post :create, job: FactoryGirl.attributes_for(:job)
# This will pass if I change the below to Job.unscoped
# OR it will pass if I add Tenant.current_id = @tenant1.id right here.
# But I shouldn't need to do either of those because
# The tenant should be set by the around_filter in application_controller.rb
# And the default_scope for Job should handle scoping
}.to change(Job,:count).by(1)
end
end
end
end
这是rspec的失败:
Failures:
1) JobsController POST create with valid attributes creates a new job
Failure/Error: expect{
count should have been changed by 1, but was changed by -1
# ./spec/controllers/test_jobs_controller_spec.rb:33:in `block (4 levels) in <top (required)>'
Finished in 0.66481 seconds
1 example, 1 failure
Failed examples:
rspec ./spec/controllers/test_jobs_controller_spec.rb:32 # JobsController POST create with valid attributes creates a new job
如果我添加一些“放置”行来直接查看 current_tenant 是谁并通过检查会话哈希,我会一直看到相同的租户 ID:
describe "POST create" do
context "with valid attributes" do
it "creates a new job" do
expect{
puts current_tenant.id.to_s
puts session[:tenant_id]
post :create, job: FactoryGirl.attributes_for(:job)
puts current_tenant.id.to_s
puts session[:tenant_id]
}.to change(Job,:count).by(1)
end
end
end
产量...
87
87
87
87
F
Failures:
1) JobsController POST create with valid attributes creates a new job
Failure/Error: expect{
count should have been changed by 1, but was changed by -1
# ./spec/controllers/test_jobs_controller_spec.rb:33:in `block (4 levels) in <top (required)>'
Finished in 0.66581 seconds
1 example, 1 failure
Failed examples:
rspec ./spec/controllers/test_jobs_controller_spec.rb:32 # JobsController POST create with valid attributes creates a new job