aboutsummaryrefslogtreecommitdiffstats
path: root/railties/test/application/current_attributes_integration_test.rb
blob: 146e96facc6e6f86fa4531bfd1811cb906759580 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
# frozen_string_literal: true

require "isolation/abstract_unit"
require "rack/test"

class CurrentAttributesIntegrationTest < ActiveSupport::TestCase
  include ActiveSupport::Testing::Isolation
  include Rack::Test::Methods

  setup do
    build_app

    app_file "app/models/current.rb", <<-RUBY
      class Current < ActiveSupport::CurrentAttributes
        attribute :customer

        resets { Time.zone = "UTC" }

        def customer=(customer)
          super
          Time.zone = customer.try(:time_zone)
        end
      end
    RUBY

    app_file "app/models/customer.rb", <<-RUBY
      class Customer < Struct.new(:name)
        def time_zone
          "Copenhagen"
        end
      end
    RUBY

    app_file "config/routes.rb", <<-RUBY
      Rails.application.routes.draw do
        get "/customers/:action", controller: :customers
      end
    RUBY

    app_file "app/controllers/customers_controller.rb", <<-RUBY
      class CustomersController < ApplicationController
        layout false

        def set_current_customer
          Current.customer = Customer.new("david")
          render :index
        end

        def set_no_customer
          render :index
        end
      end
    RUBY

    app_file "app/views/customers/index.html.erb", <<-RUBY
      <%= Current.customer.try(:name) || 'noone' %>,<%= Time.zone.name %>
    RUBY

    require "#{app_path}/config/environment"
  end

  teardown :teardown_app

  test "current customer is assigned and cleared" do
    get "/customers/set_current_customer"
    assert_equal 200, last_response.status
    assert_match(/david,Copenhagen/, last_response.body)

    get "/customers/set_no_customer"
    assert_equal 200, last_response.status
    assert_match(/noone,UTC/, last_response.body)
  end

  test "resets after execution" do
    assert_nil Current.customer
    assert_equal "UTC", Time.zone.name

    Rails.application.executor.wrap do
      Current.customer = Customer.new("david")

      assert_equal "david", Current.customer.name
      assert_equal "Copenhagen", Time.zone.name
    end

    assert_nil Current.customer
    assert_equal "UTC", Time.zone.name
  end
end