ruby-on-rails – 通过RSpec设置会话值

我当前的代码如下所示:

/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控制会话?

最佳答案 这将根据规格类型进行更改.例如,功能规范将不允许您直接修改会话.但是,控制器规格会.

您需要将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到所有规格,或specific specs使用metadata.

我经常通过将配置更改添加到定义帮助程序方法的文件中来执行此操作:

/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
点赞