Skip to content

Instantly share code, notes, and snippets.

@ka8725
Last active August 29, 2015 13:57
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 ka8725/9817055 to your computer and use it in GitHub Desktop.
Save ka8725/9817055 to your computer and use it in GitHub Desktop.
require 'active_record'
require 'minitest/autorun'
ActiveRecord::Base.establish_connection(adapter: 'sqlite3', database: 'db.sqlite3')
ActiveRecord::Schema.define do
create_table :users, force: true do |t|
t.references :company, index: true
end
create_table :companies, force: true do |t|
end
create_table :locations, force: true do |t|
t.references :company, index: true
end
end
class Location < ActiveRecord::Base
belongs_to :company
end
class Company < ActiveRecord::Base
has_many :locations
class Null
def name
'Null name'
end
def locations
[]
end
end
def name
'Real name'
end
end
class User < ActiveRecord::Base
belongs_to :company
has_many :locations, through: :company
def company
super || Company::Null.new
end
end
describe User do
before do
@company = Company.create
@location = Location.create(company: @company)
end
describe 'when user has real company' do
before do
@user = User.create(company: @company)
end
it 'returns correct name' do
assert_equal 'Real name', @user.company.name
end
it 'returns correct locations' do
assert_equal [@location], @user.locations
assert_equal @user.locations, @user.company.locations
end
end
describe 'when user does not have company' do
before do
@user = User.create
end
it 'returns name of null company' do
assert_equal 'Null name', @user.company.name
end
it 'returns locations of null company' do
assert_equal [], @user.locations
assert_equal [], @user.company.locations
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment