我目前的代码如下:
/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控制会话?
答案 0 :(得分:4)
这将根据规格类型进行更改。例如,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使用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
答案 1 :(得分:-2)
你只需要这样做:
@request.session[:session_id] = "blabla"