Rails | Apartment gem | Resets AR objects when tenant switched

I ran into a weird situation today. Active Record objects stored in vars are removed when I switched from one tenant to another on the fly. This will create a weird test-failing scenario and you never know why its happening.

def switch(name)
  yield(name)
end

@customers = [1,2,3]
switch('shiva') do |name|
  puts name
  puts @customers
end

# Gives output
# shiva
# 1
# 2
# 3

 

but when I do this

@roles     = Role.all
@customers = org.branches
@list      = [1, 2]

puts 'Role count' + @roles.count.to_s
puts 'Customer count' + @customers.count.to_s
puts 'list count' + @list.count.to_s

Apartment::Tenant.switch!(org.database_name)
puts '-------'
puts 'Role count' + @roles.count.to_s
puts 'Customer count' + @customers.count.to_s
puts 'list count' + @list.count.to_s

output is

Role count2
Customer count2
list count2
-------
Role count0
Customer count0
list count2

 

Reason

# apartment-2.2.0/lib/apartment/adapters/abstract_adapter.rb
#   Switch to a new tenant
#
#   @param {String} tenant name
#
def switch!(tenant = nil)
  run_callbacks :switch do
    return reset if tenant.nil?

    connect_to_new(tenant).tap do
      Apartment.connection.clear_query_cache
    end
  end
end
Advertisements

Add Additional Library to Faker :: RSpec :: TDD

Suppose you are working on a project in which you want to test a Applicant Model. Applicant may have any value among options in a drop-down. If you want the spec should fill the education field with the data you wish, then you can modify the Faker module. To do so, the best way is the following

create a folder in spec/ directory
create a file called ‘anything_you_want.rb’

# inside the file 'anything_you_want.rb'
class Faker::Occupation
  def self.education
    list = ['High School', 'College', 'School']
    list.sample
  end
end

Un-comment the line from the file ‘rails_helper.rb’

Dir[Rails.root.join("spec/support/**/*.rb")].each { |f| require f }