具有多租户的RSpec - 为什么这个简单的测试失败了?

时间:2013-09-18 01:40:03

标签: ruby-on-rails testing rspec multi-tenant default-scope

我在做什么

我最近在Multitenancy with Scopes(需要订阅)之后实施了多租户(使用范围)作为指导。注意:我 am 使用可怕的“default_scope”进行租户范围设定(如Ryan的Railscast所示)。一切都在浏览器中正常工作,但我的测试中很多(不是全部)都失败了,我无法弄清楚原因。

我从头开始构建身份验证(基于此Railscast:Authentication from Scratch (revised) - 需要订阅)并使用auth_token用于“记住我”功能(基于此Railscast:Remember Me & Reset Password)。

我的问题

为什么此测试失败,为什么这两个变通办法有效?我已经被困了几天了,只是想不出来。

我认为发生了什么

我正在调用Jobs #create操作,而Job.count 减少而不是增加 1.我认为正在发生的事情是工作是正在创建,然后该应用程序正在失去“租户”任务(租户降至零),测试正在计算乔布斯为错误的租户。

奇怪的是,它期待“1”并获得“-1”(而不是“0”),这意味着它正在计算(注意在前一个块中已经创建了'种子'作业,所以它是在调用#create之前可能会计数“1”,调用create动作(应该将计数增加1到2),然后丢失租户并切换到零租户,其中有0个工作。所以它:

  • 计数1(种子工作)
  • 创建工作
  • 失去了租客
  • 计算新(可能是零)租户中的0个工作

...导致Job.count发生-1变化。

您可以在下面看到,我已经通过在测试中将“.unscoped”添加到我的Job.count行来半确认了这一点。这意味着预期的工作岗位数量存在,但工作岗位不在应用程序正在测试的租户中。

我不明白的是它是如何失去租客的。

代码

我试图抓住我的代码的相关部分,并且我已经创建了一个专用的单一测试规范,以使其尽可能易于剖析。如果我可以做任何其他事情,以便在可能的回答者身上轻松完成,请告诉我该做什么!

# 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

如果我添加一些'puts'行来查看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

3 个答案:

答案 0 :(得分:1)

我认为并不是RSpec忽略了默认范围,而是通过将当前用户设置为nil来重置在过滤器中的ApplicationController中。

我在分配(...)时遇到了这个问题,之所以发生这种情况,是因为当您评估分配时,实际上已经解决了这种关系。我认为在您的情况下也可能出现这种情况。

更新:在我的情况下,我能找到的最干净的解决方案(尽管我仍然讨厌它)是通过在测试环境中不将当前用户设置为nil来让默认范围泄漏。 / p>

在您的情况下,这相当于:

def scope_current_tenant
  update_current_tenant
  yield
ensure
  Tenant.current_id = nil unless Rails.env == 'test'
end

我还没有使用您的代码对其进行测试,但这可能会有所帮助。

答案 1 :(得分:0)

我设法让我的测试通过,虽然我仍然不确定为什么他们没有开始。这是我做的:

  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)
        }.to change(Job.where(tenant_id: @tenant1.id),:count).by(1)
      end
    end
  end

我改变了:

change(Job,:count).by(1)

...为:

change(Job.where(tenant_id: @tenant1.id),:count).by(1)

注意: @ tenant1是登录管理员的租户。

我假设default_scopes将应用于RSpec,但似乎它们不是(或者至少不在“expect”块的“:change”部分)。在这种情况下,Job的default_scope是:

default_scope { where(tenant_id: Tenant.current_id) }

事实上,如果我将该行更改为:

change(Job.where(tenant_id: Tenant.current_id),:count).by(1)

......它也会过去。因此,如果我在规范中明确模仿Job的default_scope,它就会通过。这似乎证实了RSpec在Jobs上忽略了我的default_scope。

在某种程度上,我认为我的新测试是确保租户数据保持隔离的更好方法,因为我明确地检查特定租户内的计数而不是隐式检查租户的计数(假设计数在“现有租户”)。

我说我的答案是正确的,因为这是唯一的答案,如果有人遇到这个问题,我想我的答案将帮助他们解决问题。也就是说,我真的没有回答我关于为什么测试失败的原始问题。如果有人知道为什么RSpec似乎忽略了“expect”块中的default_scope,那么这可能有助于使这个问题对其他人有用。

答案 2 :(得分:0)

我和你们有同样的问题。我没有以一种让我感到舒服的方式解决问题,但仍然比验证你的RAILS_ENV更好。举个例子。

it "saves person" do
    expect {
      some_post_action
    }.to change(Person, :count).by(1)
  end

每次我尝试保存count方法时都会选择: &#34;从tenant_id为空的人员中选择计数(*)&#34;

我设法通过在更改方法中设置Person.unscoped来解决此问题,我改变了这个:

        }.to change(Person, :count).by(1)

到此:

        }.to change(Person.unscoped, :count).by(1)

这不是最佳解决方案,但我仍在努力寻找绕过default_scope的方法。