Last active
August 29, 2015 13:57
-
-
Save ka8725/9817055 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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