rails: Signed cookies not available in controller tests

This issue has been ported from the report at https://github.com/rspec/rspec-rails/issues/1658, as it can be replicated purely with Rails using public API. This test passes using Rails 4.2

Steps to reproduce

Reproduction Script
begin
  require "bundler/inline"
rescue LoadError => e
  $stderr.puts "Bundler version 1.10 or later is required. Please update your Bundler"
  raise e
end

gemfile(true) do
  source "https://rubygems.org"
  gem "rails", github: "rails/rails"
end

require "action_controller/railtie"

class TestApp < Rails::Application
  config.root = File.dirname(__FILE__)
  secrets.secret_token    = "secret_token"
  secrets.secret_key_base = "secret_key_base"

  config.logger = Logger.new($stdout)
  Rails.logger  = config.logger

  routes.draw do
    get "/" => "test#index"
  end
end

class TestController < ActionController::Base
  include Rails.application.routes.url_helpers

  def index
    render plain: "Home"
  end

  def foo_cookie
    cookies.encrypted["foo"]
  end
end

require "rails/test_help"
require "minitest/autorun"

class TestControllerTest < ActionController::TestCase
  setup do
    cookies.encrypted["foo"] = "bar"
  end

  test "accessing cookies directly" do
    get :index
    assert_equal "bar", cookies.encrypted["foo"]
  end

  test "accessing helper method" do
    get :index
    assert_equal "bar", @controller.foo_cookie
  end
end

Expected behavior

Changes to cookies.encrypted in the test setup should appear in the controller’s cookies

Actual behavior

Changes to cookies.encrypted in the test setup do not affect the controller’s cookies

System configuration

Rails version: 5.0.0, 5.0.0.1, master

Ruby version: 2.3.3

About this issue

  • Original URL
  • State: closed
  • Created 8 years ago
  • Reactions: 15
  • Comments: 17 (13 by maintainers)

Most upvoted comments

On a fresh Rails 5.2 install, I still can’t use cookies.encrypted in an integration test:

require 'test_helper'

class MyControllerTest < ActionDispatch::IntegrationTest
  test "displays current user's first name" do
    user = users(:alice)
    cookies.encrypted[:current_user] = user.id
    get '/'
    assert_select "p", user.first_name
  end
end

Results in:

Error:
MyControllerTest#test_displays_current_user's_first_name:
NoMethodError: undefined method `encrypted' for #<Rack::Test::CookieJar:0x00007fea2f04ad00>
    test/controllers/my_controller_test.rb:6:in `block in <class:DashboardControllerTest>'

I thought ActionController::TestCase is (was?) deprecated?

That commit from Jon was merged but there was a second that was related and reverted, but never fixed. See #27586