【问题标题】:session hash does not persist on rspec tests会话哈希不会在 rspec 测试中持续存在
【发布时间】:2013-02-15 10:13:55
【问题描述】:

在我的 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

我有这个 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

会话哈希似乎没有在 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)>'

我已经做了所有事情但是失败了。

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

看到这个Devise Test Helper - sign_in does not work后我解决了这个问题

我刚刚删除了所有“valid_session”方法调用。

【问题讨论】:

    标签: ruby-on-rails ruby rspec controller tdd


    【解决方案1】:

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

    session[:user_id] = @user.id
    session[:current_organization_id] = @user.organization.id
    

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

    【讨论】:

    • 啊 - 我应该要求查看测试本身。设计时也要记住一些事情:)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-04-22
    • 2023-04-03
    • 2021-05-14
    • 2011-11-17
    • 1970-01-01
    • 2018-06-25
    • 2012-02-21
    相关资源
    最近更新 更多