'Unable to set session in RSpec
Here is the file I am trying to test
module Cesid
module Access
def cesid_signout
return unless session_logged
# Method to modify the cookie
set_cookie
end
def session_logged
session[:cesid_logged]
end
end
end
Here is my rspec file
describe Cesid::Access do
context '#cesid_signout' do
let!(:access) { Class.new { extend Cesid::Access } }
it 'does nothing if not cesid logged' do
session[:cesid_logged] = false
expect(access.session_logged).to eql(false)
end
end
end
I'm just getting an error after running the rspec. The logs just keep printing this and I can't view this first line of the error
# /Users/renee.sarmiento/.rvm/gems/ruby-2.5.1@ls-member/gems/actionpack-4.2.8/lib/action_dispatch/testing/test_process.rb:14:in `session'
Any ideas? Thank you!
Solution 1:[1]
I don't have all the context in your use case.
But it is clear that you don't have access to session into your cached variable access since session is not an instance variable.
So I suggest two things:
- First, make sure that you can initiate your
sessioninstance variable into your module as explain here
module Cesid
module Access
def cesid_signout
return unless session_logged
# Method to modify the cookie
set_cookie
end
def session
@session ||= {}
end
def session_logged
@session[:cesid_logged]
end
end
end
- Then, in your spec, make sure not only to instantiate your session but also access it the right way :
context '#cesid_signout' do
let!(:access) { Class.new { extend Cesid::Access } }
it 'does nothing if not cesid logged' do
access.session[:cesid_logged] = false
expect(access.session_logged).to eql(false)
end
end
With those modification, your RSpec tests should pass.
Of course it is one way to solve your problem, but depending on your use case, other solution might work.
Hope it'll help your understanding. More insight of how module works here just in case.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Nicolas HERMET |
