0

我正在使用 Rails 3.2.13、devise 2.2.4 和 rspec 2.13.2。我有一个多租户应用程序,其中默认范围仅显示 current_user 的项目。一切似乎都在开发中,但我的测试有问题。

问题:当我在测试中创建餐点时,它显示 user_id => nil。不过,在我的开发环境中,一切正常。此外,当我进入调试模式时,当我检查@controller.current_user 时,它显示 user_id 1 已登录。由于在我的开发环境中,当我创建对象时会自动分配 user_id,我不知道为什么它在测试期间没有这样做。有任何想法吗?

这是我的简略餐食控制器规格文件:

describe MealsController do
  include Devise::TestHelpers
  describe "When logged in as user," do
    before(:each) do
      @request.env["devise.mapping"] = Devise.mappings[:user]
      @email = "someone@test.com"
      @password = "password"
      @user = User.create(email: @email, password: @password)
      sign_in @user
    end

    describe "DELETE destroy" do
      it "destroys the requested meal" do
        meal = Meal.create!("name" => "", "servings" => "2", "meal_type" => "dinner")
        expect { delete 'destroy', {:id => meal.id} }.to change(Meal, :count).by(-1)
      end
    end
  end
end

这是我的模型的一部分:

class Meal < ActiveRecord::Base
  belongs_to :user
  default_scope { where(user_id: User.current_id) }

这是我的控制器的一部分:

class MealsController < ApplicationController
  before_filter :authenticate_user!
  def destroy
    @meal = Meal.find(params[:id])
    @meal.destroy
    redirect_to meals_url, :notice => "Successfully deleted #{@meal.name}."
  end
end

而且我认为我的应用程序控制器可能是相关的:

class ApplicationController < ActionController::Base
  protect_from_forgery
  around_filter :scope_current_tenant
private
  def scope_current_tenant
    User.current_id = current_user.id
    yield
  rescue Exception
    yield
  ensure
    User.current_id = nil
  end
end

这是我在测试中间进行调试时的一些输出:

(rdb:1) @controller.current_user.id
1
(rdb:1) Meal.create!(name: "meal", meal_type: "dinner", servings: 2)
#<Meal id: 2, name: "meal", meal_type: "dinner", servings: 2, user_id: nil, created_at: "2013-06-17 06:07:34", updated_at: "2013-06-17 06:07:34">
(rdb:1) Meal.create!(name: "meal", meal_type: "dinner", servings: 2, user_id: 1)
#<Meal id: 3, name: "meal", meal_type: "dinner", servings: 2, user_id: 1, created_at: "2013-06-17 06:12:18", updated_at: "2013-06-17 06:12:18">
(rdb:1) Meal.find(3).destroy
*** NoMethodError Exception: undefined method `destroy' for nil:NilClass

所以我想我想知道为什么我的测试中的用户似乎为零,即使我正在使用 Devise 测试助手并登录,并且在我的开发环境中一切正常。

编辑: 这里有一些更多的调试器结果:

(rdb:1) Meal.find(4)
*** ActiveRecord::RecordNotFound Exception: Couldn't find Meal with id=4 [WHERE "meals"."user_id" IS NULL]
(rdb:1) Meal.find(4).destroy
*** ActiveRecord::RecordNotFound Exception: Couldn't find Meal with id=4 [WHERE "meals"."user_id" IS NULL]
(rdb:1) Meal.where(:user_id => 1).find(3)
#<Meal id: 3, name: "meal", meal_type: "dinner", servings: 2, user_id: 1, created_at: "2013-06-17 06:12:18", updated_at: "2013-06-17 06:12:18">

根据 sql 片段,“当前用户”似乎实际上是 user_id => nil。那么,如果我使用 Devise 测试助手 sign_in 函数,为什么会这样呢?

4

0 回答 0