ErwinM / acts_as_tenant

Easy multi-tenancy for Rails in a shared database setup.
MIT License
1.53k stars 263 forks source link

Make test_tenant implementation specific to thread #279

Closed mikecmpbll closed 2 years ago

mikecmpbll commented 2 years ago

At the moment test_tenant causes problems for system tests which run the server and the test in separate threads. By using Thread.current we get different test_tenant per thread.

This should also enable parrallel tests in threads.

ActsAsTenant.test_tenant = Tenant.first
# during the visit (which is async), test_tenant is set to nil by the middleware
visit foo_url
# this following line will run in the test thread while the request is running in the other thread,
# and ActsAsTenant.current_tenant will unexpectedly be nil
SomeRecord.first
sleep 2
# once the request has finished, ActsAsTenant.current_tenant will be back to the expected
# value of Tenant.first.
SomeRecord.first
mikecmpbll commented 2 years ago

should close #277 i think.

jasper502 commented 2 years ago

Any tips to implement this until this is merged?

mikecmpbll commented 2 years ago

Any tips to implement this until this is merged?

you can stick this monkey patch in config/initializers/

module ActsAsTenant
  def self.test_tenant=(tenant)
    Thread.current[:test_tenant] = tenant
  end

  def self.test_tenant
    Thread.current[:test_tenant]
  end
end
excid3 commented 2 years ago

Thanks a lot for this @mikecmpbll. That makes perfect sense and I'm pretty sure I ran into the same issue before.