Skip to content

Instantly share code, notes, and snippets.

@RyanScottLewis
Last active December 13, 2015 21:28
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 RyanScottLewis/4977059 to your computer and use it in GitHub Desktop.
Save RyanScottLewis/4977059 to your computer and use it in GitHub Desktop.
class Parser
def errors
@errors ||= []
end
end
describe Parser do
describe '#errors' do
context 'When the @errors instance variable is nil' do
before(:each) { subject.at.errors = nil }
it 'should return a new Array instance' do
subject.errors.should == []
end
end
describe 'When the @errors instance variable is not nil' do
let(:errors) { ["Something's wrong"] }
before(:each) { subject.at.errors = errors }
it 'should return the cached value of @errors' do
subject.errors.should == errors
end
end
end
end
@blatyo
Copy link

blatyo commented Feb 23, 2013

There are a couple issues with this. First, you're making the mistake of testing object oriented code in a functional manner, which doesn't work well, because object oriented code embraces state. Assuming that you mean to be writing object oriented code (since, ruby is very object oriented), the unit you should be testing is the object (or interface) and not the method. The second issue here, is that you are breaking encapsulation. The fact that your tests know about a private variable, means that they are too coupled to the implementation. That means, if you change the internals without changing the interface, you will likely still have to change your tests. What you should really be testing is the public interface of your object, that way, you are free to refactor the underlying code and still have tests that verify that you didn't break anything.

Hope that helps!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment