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

RubyRspecInstance Variables

Ruby Problem Overview


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.

Ruby Solutions


Solution 1 - Ruby

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionsteve_gallagherView Question on Stackoverflow
Solution 1 - RubyKL-7View Answer on Stackoverflow