Skip to content

Instantly share code, notes, and snippets.

@bernerdschaefer
Created June 30, 2015 19:53
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bernerdschaefer/4e6afb2501331b10e98e to your computer and use it in GitHub Desktop.
Save bernerdschaefer/4e6afb2501331b10e98e to your computer and use it in GitHub Desktop.
begin
require 'bundler/inline'
rescue LoadError => e
$stderr.puts 'Bundler version 1.10 or later is required. Please update your Bundler'
raise e
end
gemfile(true) do
source 'https://rubygems.org'
# Activate the gem you are reporting the issue against.
gem 'activerecord', '4.2.3'
gem 'sqlite3'
end
require 'active_record'
require 'minitest/autorun'
require 'logger'
# Ensure backward compatibility with Minitest 4
Minitest::Test = MiniTest::Unit::TestCase unless defined?(Minitest::Test)
# This connection will do for database-independent bug reports.
ActiveRecord::Base.establish_connection(adapter: 'sqlite3', database: ':memory:')
ActiveRecord::Base.logger = Logger.new(STDOUT)
ActiveRecord::Schema.define do
create_table :accounts, force: true do |t|
t.references :customer
t.references :customer_carrier
end
create_table :customer_carriers, force: true do |t|
t.references :customer
t.references :carrier
end
create_table :carriers
create_table :customers
end
class Account < ActiveRecord::Base
belongs_to :customer
belongs_to :customer_carrier
has_one :carrier, through: :customer_carrier
end
class Carrier < ActiveRecord::Base
end
class Customer < ActiveRecord::Base
end
class CustomerCarrier < ActiveRecord::Base
cattr_accessor :current_customer
belongs_to :customer
belongs_to :carrier
default_scope -> {
if current_customer
where(customer: current_customer)
else
all
end
}
end
class CustomerTest < ActiveSupport::TestCase
test "first pass" do
customer = Customer.create
carrier = Carrier.create
customer_carrier = CustomerCarrier.create(
customer: customer,
carrier: carrier,
)
account = Account.create(customer_carrier: customer_carrier)
CustomerCarrier.current_customer = customer
account_carrier = account.carrier
assert_equal carrier, account_carrier
end
test "second pass" do
CustomerCarrier.current_customer = nil
customer = Customer.create
carrier = Carrier.create
customer_carrier = CustomerCarrier.create(
customer: customer,
carrier: carrier,
)
account = Account.create(customer_carrier: customer_carrier)
account_carrier = account.carrier
assert_equal carrier, account_carrier
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment