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 10 years ago
  • Reactions: 15
  • Comments: 21 (16 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>'

With Rails 8 Beta 1 this might get relevant again.

In the new authentication scope we have:

def find_session_by_cookie
  Session.find_by(id: cookies.signed[:session_id])
end

But Rack::Test::CookieJar doesn’t define signed.

eval error: undefined method `signed' for an instance of Rack::Test::CookieJar

I monkey patched in my test helpers like it’s 2009:

ENV["RAILS_ENV"] ||= "test"
require_relative "../config/environment"
require "rails/test_help"

module ActiveSupport
 class TestCase
   # Run tests in parallel with specified workers
   parallelize(workers: :number_of_processors)

   # Setup all fixtures in test/fixtures/*.yml for all tests in alphabetical order.
   fixtures :all

   # Add more helper methods to be used by all tests here...
   def login_as(user)
     session = user.sessions.create!(user_agent: "test", ip_address: "127.0.0.1")
     Current.session = session
     cookies[:session_id] = session.id
   end

   def encrypted_password(password = "password")
     BCrypt::Password.create(password, cost: 4)
   end

   def assert_logged_in
     assert Current.session.present?, "Expected to be logged in, but wasn't"
   end

   def assert_not_logged_in
     assert_not Current.session.present?, "Expected not to be logged in, but was"
   end
 end
end

# Monkey-patch the Authentication concern for test environment
module Authentication
 private
   def find_session_by_cookie
     Session.find_by(id: cookies[:session_id])
   end
end

Maybe we do something here? Any suggestions? Implement a signed on the Rack::Test::CookieJar?

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

Sorry Rafael, I was overworked and out of sleep. I meant Rack::Test::CookieJar has no signed instance method (corrected my comment). With the monkey patch I worked around that. I created that issue:

https://github.com/rails/rails/issues/53207

Can you provide an example of what doesn’t work so we can run and open a new issue? ActionDispatch::Cookies::CookieJar for sure defines signed

>> cookies = ActionDispatch::Cookies::CookieJar.build({}, {})
=> #<ActionDispatch::Cookies::CookieJar:0x0000ffff6b4ac868 @committed=false, @cookies={}, @delete_cookies={}, @request={}, @set_cookies={}>
>> cookies.method(:signed)
=> #<Method: ActionDispatch::Cookies::CookieJar(ActionDispatch::Cookies::ChainedCookieJars)#signed() /workspaces/rails/actionpack/lib/action_dispatch/middleware/cookies.rb:253>