Request spec for rails authentication (I am going crazy)
So I am new to ruby on rails and I used rails authentication to generate the authentication of my app. Now I am writing an rspec for the rails generated sessions_controller. I am having trouble targeting the Session.find_signed(token, purpose: :session)from authentication concern generated by rails. My code coverage says that my test isn't hitting that only line.
concern/authentication.rb
def find_session_by_cookie
token = cookies.signed[:session_id]
return unless token
Session
.find_signed(token, purpose: :session)
end
How do write an rspec for this line?
here is my current spec for sessions_controller:
RSpec
.describe 'SessionsController' do
let(:user) { create(:user) }
describe 'GET /session/new' do
before do
get '/session/new'
end
it 'renders successfully when unauthenticated' do
expect(response).to have_http_status(:ok)
end
end
describe 'POST /session' do
context 'with valid credentials' do
before do
post '/session', params: {
email_address: user.email_address,
password: user.password
}
end
it 'creates a session and redirects to root' do
expect(response).to redirect_to(root_path)
expect(user.sessions.reload).not_to be_empty
end
end
context 'with invalid credentials' do
before do
post '/session', params: {
email_address: 'nonexistent@example.com',
password: 'wrong'
}
end
it 'redirects to new_session_path with alert' do
expect(response).to redirect_to(new_session_path)
expect(flash[:alert]).to eq('Try another email address or password.')
end
end
context 'when rate limited' do
before do
allow(
Rails
.cache).to receive(:increment).and_return(11)
post '/session', params: { email_address: user.email_address, password: 'wrong' }
end
it 'blocks requests after the configured limit' do
expect(response).to redirect_to(new_session_path)
expect(flash[:alert]).to eq('Try again later.')
end
end
end
describe 'DELETE /session' do
context 'when authenticated' do
include_context :authenticated_current_session
before do
delete '/session'
end
it 'destroys the current session and redirects with see other' do
expect(response).to redirect_to(new_session_path)
expect(response).to have_http_status(:see_other)
end
end
context 'when unauthenticated' do
before do
delete '/session'
end
it 'redirects to new_session_path' do
expect(response).to redirect_to(new_session_path)
expect(response).to have_http_status(:found)
end
end
end
end
UPDATE: I convinced my seniors to just use ActionDispatch and manually sign the cookie because It's so hard to mock a signed cookie in a request spec.
u/Dosbrostacosbaby — 1 month ago