small medium large xlarge

24 Nov 2017, 09:13
Mitchell Gould (2 posts)

I have added a feature that does not allow users to access carts that are not in the session:


class CartsController < ApplicationController
 before_action :check_cart, only: [:show]


    def check_cart
      redirect_to store_index_url, notice: "Invalid Cart" unless session[:cart_id] ==

However, now I can’t get one of my tests in demo/tests/controllers/carts_controller_test.rb to pass:

require 'test_helper'

class CartsControllerTest < ActionDispatch::IntegrationTest
  setup do
    @cart = carts(:one)

  test "should show cart" do
    get cart_url(@cart)
    assert_response :success

This is because session[:cart_id] is blank as I have checked it. So the session[:cart_id] does not match and is being redirected. How can I get this test to pass?

24 Nov 2017, 21:18
David Copeland (491 posts)

In past versions of Rails you could set the session in the test. That is no longer supported, so you must navigate the URLs that would set it. This stackoverflow question gives the gist of it, but you’ll need to actually log in and establish a cart inside your test.

You must be logged in to comment