Last active
September 11, 2018 17:59
-
-
Save frankywahl/4b3e731e8db9f7443a55 to your computer and use it in GitHub Desktop.
Playing with instance variables
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 'pry' | |
require 'rspec' | |
# Not using class variables | |
class PersonNoVar | |
@counter = 0 | |
class << self | |
attr_accessor :counter | |
end | |
def initialize | |
self.class.counter += 1 | |
end | |
def self.count | |
counter | |
end | |
end | |
class StudentNoVar < PersonNoVar | |
end | |
## Using Class Variables | |
class Person | |
@@counter = 0 | |
def initialize | |
@@counter += 1 | |
end | |
def self.count | |
@@counter | |
end | |
end | |
class Student < Person | |
end | |
describe 'counter' do | |
context 'with class variables' do | |
subject do | |
5.times { Person.new } | |
3.times { Student.new } | |
end | |
it 'works' do | |
expect { subject }.to change { Person.count }.by(8) | |
end | |
end | |
context 'without class variables' do | |
subject do | |
5.times { PersonNoVar.new } | |
3.times { StudentNoVar.new } | |
end | |
it 'works' do | |
expect { subject }.to change { PersonNoVar.count }.by(8) | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment