Current.user is set to nil after a post request in mini test

167 Views Asked by At

I'm using Current Attributes: https://api.rubyonrails.org/classes/ActiveSupport/CurrentAttributes.html

class Current < ActiveSupport::CurrentAttributes
  attribute :account, :user
  attribute :request_id, :user_agent, :ip_address

  resets { Time.zone = nil }

  def user=(user)
    super
    self.account = user.account
    Time.zone    = user.time_zone
  end
end

Using Minitest, when I make a post request, Current is set to an empty hash. Get requests are ok. I found that this is supposed to happen with background jobs: https://github.com/rails/rails/issues/36298 - and the hack on the last post works but I would like to find out if there are any other options.

But can't figure out why it's happening with post requests.

Example test:

  test "create new contact" do
    Current.user = users(:standard_user)

    new_contact_params = {contact: {first_name: "first name", last_name: "last name"}}
    post contacts_path, params: new_contact_params
    
    Current.user # Current user is nil here so I can't do something like Current.user.contacts.any?

    assert_response :success
  end
1

There are 1 best solutions below

1
borisano On

The reason why Current.user is nil in your test is because Minitest runs in a separate thread from the main application thread. When you make a post request, the request is handled by the main application thread, but the CurrentAttributes object is not available in the separate thread.

To fix this, you can use the around hook in Minitest to run the request in the main application thread. Here is an example:

class CreateContactTest < ActiveSupport::TestCase
  test "create new contact" do
    Current.user = users(:standard_user)

    around do |example|
      in_main_thread do
        example.run
      end
    end

    new_contact_params = {contact: {first_name: "first name", last_name: "last name"}}
    post contacts_path, params: new_contact_params

    assert_response :success
    assert Current.user.contacts.any?
  end
end