title: RSpec: How to stub methods and method-chains
body: <p>I have a singleton class that is accessed by a number of other classes and controllers to determine behaviour. How do I set the singleton values in my tests so I can test the behaviour. Example code below where Setting is a Singleton class, which is database backed and stores application wide settings and these settings can be changed by administrators. Floodgate is a class that accesses the settings.</p>
  
  <pre><code>class Setting
    def instance
      @setting ||= new
    end
  end
  
  class Floodgate
    def self.whitelist
      Setting.instance.flood_gate_whitelist
    end
  end
  </code></pre>
  
  <p>Below are some tests for Floodgate which need to access the Settings database values.</p>
  
  <pre><code>describe Floodgate do
    let(:setting) { Class.create(Setting).instance }
  
  describe ".whitelist" do
    it "returns a list of values on the Settings floodgate whitelist" do
      expect(Floodgate.whitelist).to eq 'google'
    end
  end
  
  describe ".allow_traffic_source?" do
    it "returns true if traffic source is on the white list" do
      expect(Floodgate.allow_traffic_source?('google')).to eq true
    end
  
    it "returns false if traffic source is not on the white list" do
      expect(Floodgate.allow_traffic_source?('facebook')).to eq false
    end
  end
  </code></pre>
  
  <p>The first and second test above fail, because Setting.flood_gate_whitelist is nil. In the Floodgate tests, how do I set it so that it persists, atm there is no record in the d/b. I tried explicitly setting it as below and when I use create, the error response is undefined method 'create'.</p>
  
  <pre><code>let(:setting) { Class.new(Setting, flood_gate_whitelist: 'google').instance } 
  </code></pre>