Skip to content

NoTenantSet error raised within an ActsAsTenant.without_tenant block (RSpec + Rails) #338

@its-fern

Description

@its-fern

Currently running ActsAsTenant v 1.0.1 on a Rails 7.1 app. We use rspec for testing and recently upgraded rspec-rails from 6.1.2 to 6.1.3. We started running into NoTenantSet errors on this upgrade when we were not before.

For some context, we have a helper set up that allows devs to include a tag in the rspec context to disable the tenant check:

RSpec.configure do |config|
  # Acts as tenant support - check out documenation here:
  # https://github.com/ErwinM/acts_as_tenant#testing
  config.around do |example|
    if example.metadata[:skip_multitenancy]
      ActsAsTenant.without_tenant do
        # ActsAsTenant::Errors::NoTenantSet error raised here
        example.run
      end
    else
      ## ...
    end
  end
end

Devs can then write specs that ignore the tenant check like so:

require "rails_helper"

RSpec.describe SomeModel, type: :model do
  context "without multi-tenancy", skip_multitenancy: true do
    it "allows creating models" do
      expect { SomeModel.create!(name: "foo") }.to change(SomeModel, :count).by(1)
    end
  end

  context "with multi-tenancy" do 
    it "raises an error if no tenant is set" do
      expect { SomeModel.create!(name: "foo") }.to raise_error(ActsAsTenant::Errors::NoTenantSet)
    end
  end
end

I did some digging and I think this might be related to this PR rspec/rspec-rails#2752 (full changelog here). The ActsAsTenant.unscoped? flag is being reset somehow (confirmed this by stepping through the code) so this code block raises:

if ActsAsTenant.should_require_tenant? && ActsAsTenant.current_tenant.nil? && !ActsAsTenant.unscoped?
raise ActsAsTenant::Errors::NoTenantSet
end

Any help is appreciated here, and I'm happy to provide more info where I can!

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions