1

只是无法弄清楚如何测试使用私有 ApplicationController 方法的操作。解释:

用户拥有并属于许多组织(通过角色),反之亦然。一个组织有一堆相关的实体,但在应用程序中,用户一次只处理一个组织,所以对于我所有的控制器方法,我想与当前组织进行范围。所以在我的 ApplicationController 中:

private

# Returns the organisation that is being operated on in this session.
def current_org
  # Get the org id from the session. If it doesn't exist, or that org is no longer operable by the current user,
  # find an appropriate one and return that.
  if (!session[:current_organisation_id] || !current_user.organisations.where(['organisations.id = ?', session[:current_organisation_id]]).first)
    # If an org doesn't exist for this user, all hope is lost, just go to the home page
    redirect_to '/' if (!current_user.organisations.first)
    # Otherwise set the session with the new org
    session[:current_organisation_id] = current_user.organisations.first.id;
  end
  # Return the current org!
  current_user.organisations.first
end

首先,我不知道这是否是确定范围的最佳方式。我喜欢一些优雅的 default_scope 东西,但是使用会话变量这似乎有问题。无论如何,上面让我在控制器中执行此操作:

class HousesController < ApplicationController
  def index
    @houses = current_org.houses
  end
end

所以现在我想使用 rspec 来测试我的控制器。如何确保可以调用 current_org 方法并返回其中一个 factory_girl 组织模型,以便编写规范。我只是对如何最好地将工厂、规范、操作和 AppControlled 方法结合在一起感到困惑。

4

0 回答 0