【问题标题】:Setting a session value through RSpec通过 RSpec 设置会话值
【发布时间】:2017-07-07 15:55:57
【问题描述】:

我当前的代码如下所示:

/spec/support/spec_test_helper.rb

module SpecTestHelper
  def login_admin
    user = FactoryGirl.create(:user, type: 0)
    session[:user_id] = user.id
  end
end

/app/controllers/application_controller.rb

def current_user
  if session[:user_id].nil?
    render plain: 'Error', status: :unauthorized
  else
    @current_user ||= User.find(session[:user_id])
  end
end

不幸的是,在 current_user 方法中 session 总是空的。有没有办法通过 RSpec 控制会话?

【问题讨论】:

  • 功能规格或控制器规格?
  • 你如何/在哪里打电话给login_admin
  • 在banners_controller_spec中,在它“...”做块
  • 奇怪的是你不必做任何其他事情。 (github.com/rails/rails/blob/…)
  • 可能是我在 before_action 过滤器中进行检查?

标签: ruby-on-rails ruby session rspec


【解决方案1】:

这将根据规格类型而改变。例如,feature 规范将不允许您直接修改会话。但是,controller 规范会。

您需要将helper methods module 包含到您的示例组中。假设你有一个WidgetsController

require 'support/spec_test_helper'

RSpec.describe WidgetsController, type: :controller do
  include SpecTestHelper

  context "when not logged in" do
    it "the request is unauthorized" do
      get :index
      expect(response).to have_http_status(:unauthorized)
    end
  end

  context "when logged in" do
    before do
      login_admin
    end

    it "lists the user's widgets" do
      # ...
    end
  end
end

您也可以automatically include the module 进入所有规格,或使用metadata specific specs

我经常通过将配置更改添加到定义辅助方法的文件中来做到这一点:

/spec/support/spec_test_helper.rb

module SpecTestHelper
  def login_admin
    user = FactoryGirl.create(:user, type: 0)
    session[:user_id] = user.id
  end
end

RSpec.configure do |config|
  config.include SpecTestHelper, type: :controller
end

【讨论】:

  • 我遇到了同样的问题,但对我没有帮助,我遇到了同样的错误。 “#<:examplegroups:>
  • 您应该在 SpecTestHelper 中包含 require 'rails_helper'
猜你喜欢
  • 2014-04-22
  • 2012-01-31
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-02-25
  • 2018-06-16
  • 2014-12-11
  • 2016-03-20
相关资源
最近更新 更多