Rails 5 Rspec set session variable
Asked Answered
B

2

7

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?

Bottomless answered 14/1, 2018 at 4:35 Comment(3)
Please remove the Capybara tag. Capybara isn’t used for request specs.Heirloom
Can't you do something like: request.session[:user_id] = 1 in a before(:each) block?Kemppe
Manage to find an answer?Adhern
V
1

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
Vanir answered 12/7, 2018 at 8:49 Comment(1)
@Linus which should be the same, as Ruby merges all puts all hash arguments into one hash anyways.Vanir
C
0

For Rails < 5, this solution works

def _set_session(key, value)
  Warden.on_next_request do |proxy|
    proxy.raw_session[key] = value
  end
end

_set_session(:access_acount_id, user.id)

Example

def _set_session(key, value)
  Warden.on_next_request do |proxy|
    proxy.raw_session[key] = value
  end
end

context 'When there is something' do
  let(:yesterday) { 1.day.ago }
  let(:updates_enabled) { true }

  before do
    _set_session(:access_acount_id, user.id)
    login_as(user, scope: :user)
  end

  it 'does not update records' do
    visit dashboard_path
    expect(page).to have_css('.popup#my-popup')
  end
end
Chuckhole answered 1/5, 2020 at 11:43 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.