Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
class Parser
def errors
@errors ||= []
describe Parser do
describe '#errors' do
context 'When the @errors instance variable is nil' do
before(:each) { = nil }
it 'should return a new Array instance' do
subject.errors.should == []
describe 'When the @errors instance variable is not nil' do
let(:errors) { ["Something's wrong"] }
before(:each) { = errors }
it 'should return the cached value of @errors' do
subject.errors.should == errors

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