以下是我的规格和类的代码:
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
然后我收到一条友好的规范失败消息:
Game#no_books? should return true if books attribute is empty
Failure/Error: @game.no_books?.should be_true
expected false to be true
就好像在使用值初始化属性书之前调用该方法一样。有人可以向我解释这里会发生什么吗?
答案 0 :(得分:0)
您的no_books?
实现正在检查中直接使用实例变量,绕过您的存根。如果您将no_books?
更改为返回books.empty?
,则会调用存根。
如果您确实 希望继续使用实例变量,则可以@game
通过instance_variable_set
进行设置,如下所示:
@game.instance_variable_set("@books", [])