RubyRspec: 测试实例变量而不向源代码添加访问器

我正在试验以下方法:

def unprocess_move(board, move)
if move[0].instance_of?(Array)
multi_move = @multi_move.pop(2).reverse
multi_move.each do |single_move|
unapply_move(board, single_move)
end
else
board = unapply_move(board, move)
end
board
end

其中我想为@multi _ move 设置状态,但是我不想仅仅为了测试而添加一个访问器。有没有不需要访问器的方法?谢谢。

52109 次浏览

You can use Object#instance_variable_get method to get value of any instance variable of the object like that:

class Foo
def initialize
@foo = 5 # no accessor for that variable
end
end


foo = Foo.new
puts foo.instance_variable_get(:@foo)
#=> 5

And Object#instance_variable_set can be used to set instance variable values:

foo.instance_variable_set(:@foo, 12)
puts foo.instance_variable_get(:@foo)
#=> 12