title: Stubbing instance variables in RSpec 3.2
body: <p>I'm using RSpec 3.2 in Rails and wondering how I can stub instance variables if they are not publicly made accessible by a getter method (e.g. using <code>attr_accessor</code> or similar). </p>
  
  <p>Consider the simple example below -</p>
  
  <pre><code>require 'rails_helper'
  
  class A
    def initialize
      @x = 3
    end
  
    def add(n)
      sum = @x + n
      puts "Sum is #{sum}"
      sum
    end
  end
  
  
  RSpec.describe A do
    before(:all) do
      @a = A.new
    end
  
    it 'computes the sum correctly' do
      # For this test I want to stub the value of @x and return 5
      allow(@a).to receive(:x) { 5 }
      # 5 + 8 should return 13
      expect(@a.add(8)).to eq(13)
    end
  end
  </code></pre>
  
  <p>Trying to stub <code>@x</code> is not possible in this scenario as the class never never receives a message or method call for <code>x</code>. The RSpec output confirms this -</p>
  
  <pre><code>Failures:
  
    1) A computes the sum correctly
       Failure/Error: allow(@a).to receive(:@x) { 5 }
         #&lt;A:0x007fe6e66ab8d0 @x=3&gt; does not implement: @x
       # ./spec/unit/test_spec.rb:25:in `block (2 levels) in &lt;top (required)&gt;'
  </code></pre>
  
  <p>I could work around this by making the instance variable <code>@x</code> accessible (<code>attr_accesssor :x</code>) and replacing the call to <code>@x</code> with <code>self.x</code>, but that seems hacky and may not be possible in my more complex implementation.</p>
  
  <p>Is there a better way to stub this?</p>
  
  <p>Thanks!</p>