title: Ruby. Mocking in RSpec
body: <p>I have a problem with mocking. I have class DistanceMatrix and I would
  like to indicate which method form_matrix was called in if/else
  statement. I need to use mocha and RSpec. Any ideas?</p>
  
  <pre><code>class DistanceMatrix
  
   def initialize(*args)
      if args[0].class == String
        form_matrix(get_data_from_yaml(args[0], args[1]))
      elsif args[0].class == Array || args[0] == nil
        form_matrix(get_data_from_db(args[0]))
      end
   end
  
   def form_matrix(...)
    ...
   end
  
  end
  </code></pre>
  
  <p>it tried:</p>
  
  <pre><code>describe DistanceMatrix, "when mocking ..." do
    it "should do call form_matrix" do
      DistanceMatrix.any_instance.expects(:form_matrix).with([1]).once
      DistanceMatrix.any_instance.expects(:get_data_from_yaml).with("file_name.yml").once.returns([1])
      DistanceMatrix.new("file_name.yml")
    end
  end
  </code></pre>
  
  <p>but got error:</p>
  
  <pre><code>Failures:
    1) DistanceMatrix when mocking ... should do call form_matrix
       Failure/Error: DistanceMatrix.new("file_name.yml")
       unexpected invocation: #&lt;AnyInstance:DistanceMatrix&gt;.get_data_from_yaml('file_name.yml', nil)
       unsatisfied expectations:
       - expected exactly once, not yet invoked: #&lt;AnyInstance:DistanceMatrix&gt;.get_data_from_yaml('file_name.yml')
       - expected exactly once, not yet invoked: #&lt;AnyInstance:DistanceMatrix&gt;.form_matrix([1])
       satisfied expectations:
       - allowed any number of times, already invoked once: #&lt;DistanceMatrix:0x9e48b40&gt;.get_optimal_route(any_parameters)
       - allowed any number of times, already invoked once: #&lt;Database::Distances:0x9d59798&gt;.load_distances(any_parameters)
       # ./distance_matrix.rb:18:in `initialize'
       # ./tsp_algorithm_spec.rb:253:in `new'
       # ./tsp_algorithm_spec.rb:253:in `block (2 levels) in &lt;top (required)&gt;'
  Finished in 0.25979 seconds
  </code></pre>
  
  <p>I found that in RSpec we should use not .expects() but .should_receive(), so I tried:</p>
  
  <pre><code>describe DistanceMatrix, "when mocking ..." do
    it "should do call form_matrix" do
      DistanceMatrix.any_instance.should_receive(:form_matrix).with([1])
      DistanceMatrix.any_instance.should_receive(:get_data_from_yaml).with("file_name.yml").and_return([1])
      DistanceMatrix.new("file_name.yml")
    end
  end
  </code></pre>
  
  <p>but got new failure:</p>
  
  <pre><code>Failures:
    1) DistanceMatrix when mocking ... should do call form_matrix
       Failure/Error: DistanceMatrix.any_instance.should_receive(:form_matrix).with([1])
       (#&lt;Mocha::ClassMethods::AnyInstance:0x96356b0&gt;).form_matrix([1])
           expected: 1 time
           received: 0 times
       # ./tsp_algorithm_spec.rb:251:in `block (2 levels) in &lt;top (required)&gt;'
  
  Finished in 0.26741 seconds
  </code></pre>