Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails 5 Rspec set session variable

I have a request test spec which tests a POST request.

In my PaymentController (which handles the POST request), i have

before_action :require_user, :require_order

which basically gets the user and order based on the session.

Any idea how i can set session variable(user_id and order_id) in my request test spec?

like image 731
Shaun Wan Avatar asked Jan 14 '18 04:01

Shaun Wan


1 Answers

Since Rails 5.0 the best way is to use the keyword arguments in the controller/request tests:

get :index, params: { ... }, session: { user_id: 1, ... }

If you are using a authentication library like Devise, Clearance and such, there are various helpers to stub a logged in user, see here the Documentation for Devise:

before(:each) do
  # or def setup if using minitest
  @request.env["devise.mapping"] = Devise.mappings[:user]
  sign_in User.create(...)
end
like image 148
stwienert Avatar answered Oct 22 '22 10:10

stwienert