Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
50 changes: 50 additions & 0 deletions spec/activerecord-multi-tenant/query_rewriter_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -67,6 +67,31 @@
end
end

it 'when tenant_id is ID' do
expected_query = <<-SQL.strip
UPDATE "projects" SET "name" = $1 WHERE "projects"."id" IN
(SELECT "projects"."id" FROM "projects"
INNER JOIN "managers" ON "managers"."project_id" = "projects"."id"
and "managers"."account_id" = :account_id
WHERE "projects"."account_id" = :account_id
AND "projects"."account_id" = :account_id
)
SQL

expect do
MultiTenant.default_tenant_class = Account
MultiTenant.with(account.id) do
Project.joins(:manager).update_all(name: 'New Name')
end
end.to change { project.reload.name }.from('Project 1').to('New Name')

@queries.each do |actual_query|
next unless actual_query.include?('UPDATE "projects" SET "name"')

expect(format_sql(actual_query)).to eq(format_sql(expected_query.gsub(':account_id', account.id.to_s)))
end
end

it 'updates a limited number of records with expected query' do
# create 2 more projects
Project.create(name: 'project2', account: account)
Expand Down Expand Up @@ -148,6 +173,31 @@
end
end

it 'when tenant_id is ID' do
expected_query = <<-SQL.strip
DELETE FROM "projects" WHERE "projects"."id" IN
(SELECT "projects"."id" FROM "projects"
INNER JOIN "managers" ON "managers"."project_id" = "projects"."id"
and "managers"."account_id" = :account_id
WHERE "projects"."account_id" = :account_id
AND "projects"."account_id" = :account_id
)
SQL

expect do
MultiTenant.default_tenant_class = Account
MultiTenant.with(account.id) do
Project.joins(:manager).delete_all
end
end.to change { Project.count }.from(3).to(1)

@queries.each do |actual_query|
next unless actual_query.include?('DELETE FROM ')

expect(format_sql(actual_query)).to eq(format_sql(expected_query.gsub(':account_id', account.id.to_s)))
end
end

it 'delete_all the records without a current tenant' do
expect do
Project.joins(:manager).delete_all
Expand Down