0

这是我的规格和课程的代码:

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

就好像在使用值初始化属性书之前调用了该方法。有人可以向我解释这里发生了什么吗?

4

1 回答 1

0

您的no_books?实现在其检查中直接使用实例变量,绕过您的存根。如果您更改no_books?为 return books.empty?,它将改为调用存根。

如果你真的,真的想继续使用实例变量,你可以像这样设置@gameinstance_variable_set

@game.instance_variable_set("@books", [])
于 2012-05-14T02:43:56.930 回答