会话哈希在rspec测试中不会持久存在

nei*_*ion 3 ruby tdd controller rspec ruby-on-rails

在我的people_controller_spec.rb中我有

before(:each) do
    @office = FactoryGirl.create(:office)
    @organization = FactoryGirl.create(:organization)
    @user = FactoryGirl.create(:user, organization: @organization)

    @request.session['user_id'] = @user.id
    @request.session['current_organization_id'] = @user.organization.id
  end
Run Code Online (Sandbox Code Playgroud)

我有这个application_controller.rb

class ApplicationController < ActionController::Base

  protect_from_forgery

  private

  def current_user
    @current_user ||= User.find(session[:user_id]) if session[:user_id]
  end

  def current_organization
    if session[:current_organization_id]
      Organization.find(session[:current_organization_id])
    else
      @current_organization ||= Organization.find(current_user.organization_id)
    end
  end

  helper_method :current_user
  helper_method :current_organization
end
Run Code Online (Sandbox Code Playgroud)

会话哈希似乎没有在application_controller.rb中持久存在,这就是为什么我得到这些类型的测试错误,其中application_controller.rb中的@current_user是nil

  6) PeopleController index sorts all people alphabetically by first_name
     Failure/Error: get :index, {search: {meta_sort: "first_name.asc"}}, valid_session
     NoMethodError:
       undefined method `organization_id' for nil:NilClass
     # ./app/controllers/application_controller.rb:15:in `current_organization'
     # ./app/controllers/people_controller.rb:107:in `get_orgs'
     # ./spec/controllers/people_controller_spec.rb:71:in `block (3 levels) in <top (required)>'
Run Code Online (Sandbox Code Playgroud)

我已经做了一切但失败了.

我使用rails(3.2.9)和rspec-rails 2.12.2

我在看到这个设计测试助手后解决了问题- sign_in不起作用

我刚刚删除了所有"valid_session"方法调用.

roo*_*roo 5

在您的before :each块中设置会话:

session[:user_id] = @user.id
session[:current_organization_id] = @user.organization.id
Run Code Online (Sandbox Code Playgroud)

这使用rspec控制器宏提供的会话助手.此外,我不确定会话是否HashWithIndifferentAccess类似,params但无论哪种方式保持使用相同的密钥类型.