Ruby Rspec:测试实例变量而不向源添加访问器

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9364157/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-06 04:47:39  来源:igfitidea点击:

Ruby Rspec : Testing instance variables without adding an accessor to source

rubyrspecinstance-variables

提问by steve_gallagher

I'm trying to test the following method:

我正在尝试测试以下方法:

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

where I want to set the state for @multi_move, but I don't want to add an accessor just for testing. Is there a way to do so without the accessor? Thanks.

我想为@multi_move 设置状态,但我不想添加仅用于测试的访问器。有没有办法在没有访问器的情况下做到这一点?谢谢。

回答by KL-7

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

您可以使用Object#instance_variable_get方法来获取对象的任何实例变量的值,如下所示:

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_setcan be used to set instance variable values:

并且Object#instance_variable_set可用于设置实例变量值:

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