public
Last active

  • Download Gist
parser.rb
Ruby
1 2 3 4 5 6 7
class Parser
def errors
@errors ||= []
end
end
parser_spec.rb
Ruby
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29
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

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!

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.