Here are some steps and examples demonstrating how to test cookie expiration at different testing levels:
1. Controller or Request Testing
At this level, you primarily focus on how the controller sets cookies and ensures they expire after the expected time.
Example
Assume you have a controller SessionsController that sets a cookie when a user logs in:
rubyclass SessionsController < ApplicationController def create cookies.signed[:user_id] = { value: @user.id, expires: 2.hours.from_now } redirect_to root_path end end
You can write a test to simulate the passage of time and verify that the cookie expires correctly:
rubyrequire 'rails_helper' RSpec.describe SessionsController, type: :controller do describe "POST #create" do before do @user = FactoryBot.create(:user) post :create, params: { user: { username: @user.username, password: 'secret' } } end it "sets a signed user_id cookie with an expiry time" do expect(cookies.signed[:user_id]).to eq(@user.id) expect(response.cookies['user_id']).to be_present end it "expires the cookie after 2 hours" do travel_to 3.hours.from_now expect(cookies.signed[:user_id]).to be_nil expect(response.cookies['user_id']).not_to be_present end end end
In this test, we use the travel_to method to advance time, which is a Rails method provided for simulating time progression in tests.
2. Integration Testing
If you want to test cookie expiration within a broader application flow (such as user behavior after login), you can use integration tests to achieve this.
Example
rubyrequire 'rails_helper' RSpec.describe "User login and session expiration", type: :feature do scenario "User logs in and then the session expires after 2 hours" do user = FactoryBot.create(:user) visit login_path fill_in "Username", with: user.username fill_in "Password", with: 'secret' click_button "Login" expect(page).to have_content("Welcome, #{user.username}") travel_to 3.hours.from_now visit some_protected_path expect(page).to have_content("Please login to continue") expect(page).not_to have_content("Welcome, #{user.username}") end end
In this integration test, we first simulate user login, then use the travel_to method to advance time beyond the cookie's expiration time, and verify that the user is redirected to the login page and the welcome message no longer appears.
Summary
Testing cookie expiration in RSpec can be performed at different testing levels, with the key being to use time simulation methods such as travel_to to ensure you can check application behavior at different time points. Such tests help ensure your application correctly handles session and cookie management, enhancing security and user experience.