small medium large xlarge

Generic-user-small
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:

depot/app/controllers/carts_controller.rb

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

private

    def check_cart
      redirect_to store_index_url, notice: "Invalid Cart" unless session[:cart_id] == @cart.id
    end
end

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)
  end

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

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

Dmfcb_pragsmall
24 Nov 2017, 21:18
David Copeland (487 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