Here is the code for my specs and class:
describe Game do
before(:each) do
@game = Factory.build(:game)
end
describe '#no_books?' do
it 'should return true if books attribute is empty' do
@game.stub(:books).and_return([])
@game.no_books?.should be_true
end
it 'should return false if books attribute is present' do
@game.no_books?.should be_false
end
end
end
class Game
attr_reader :books
def initialize
@books = parse_books
end
def no_books?
@books.empty?
end
protected
def parse_books
# return books
end
end
I then get a friendly spec failure message:
Game#no_books? should return true if books attribute is empty
Failure/Error: @game.no_books?.should be_true
expected false to be true
It’s as if that method is getting called before the attribute books get initialized with a value. Can someone explain to me what’s going here?
Your
no_books?implementation is using the instance variable directly in its check, bypassing your stub. If you changeno_books?to returnbooks.empty?, it will call the stub instead.If you really, really want to keep using the instance variable, you can set it in
@gameviainstance_variable_setlike this: