2
votes

I have a multi-tenancy app using ascts_as_tenant. I am trying to write a spec that tests a scope. So I want to test the output of User.active.

In general this works fine with code such as the following

it "returns a correct active user" do
  user_active = Fabricate(:user, curremp: true)
  user_scope2_active = Fabricate(:user, curremp: true)
  user_not_active = Fabricate(:user, account_id: user_active.account_id, curremp: false)
  expect(User.active).should include(user_active)
  #expect(User.active).to_not include(user_scope2_active)
  expect(User.active).to_not include(user_not_active) 
end

However, I'm lost on how I get it to use the acts_as_tenant functionality to use a current_tenant and to therefore validate it only lists active users from one tenant. I'm sure this has been done before but I haven't found any documentation on it as yet.

Therefore how do I test acts_as_tenant user model with rspec?

2

2 Answers

9
votes

This is what we do:

In general, you don't need to deal with scoping your information to tenants in your unit tests. So just write these tests as if there was no scoping going on.

The only exception to this is if you want to specifically test something related to the scoping. We do this very rarely. Acts_as_tenant has its own test suite to test the scoping (but then I would say that, since I wrote it ;).

If you must deal with AaT in your unit tests you can set the current_tenant directly:

ActsAsTenant.current_tenant = Account.first

It's then important that you clean up that tenant in an after filter (set it to nil), or you will be in debug hell.

0
votes

I found it helpful to ensure that the correct error messages are thrown in case something funky happens with the tenant, e.g.:

    before(:each) do
      ActsAsTenant.current_tenant = FactoryBot.create(:account)
    end

    it 'is not valid without an account' do
      foo = FactoryBot.create(:foo)
      expect { foo.account = nil }.to raise_error ActsAsTenant::Errors::TenantIsImmutable
    end