[rspec-users] Surprising mock behavior

Mark Thomson mark.thomson at ieee.org
Fri Oct 24 00:12:00 EDT 2008


Pat Maddox wrote:
> Can you please post an example of the spec and production code that
> isn't behaving as you expect?
>
> Pat
>   

Sure, sorry been tied up with business travel this week. Here's my 
controller...


----
class SubscribersController < ApplicationController
 
  def test
 
    file = File.new("test.txt", "w")
   
   
    file.puts "one"
    file.puts "two"
    file.puts "three"
    file.puts "four"
    file.puts "five"
    file.puts "six"

    render :action => "index"

  end
 
end

-----

and a spec containing two examples that illustrate what I was talking 
about -


-----

describe SubscribersController do

    it "does not pass" do
   
        file = mock('file')
        File.stub!(:new).and_return(file)
       
        file.should_receive(:puts).with("one")
        file.should_receive(:puts).with("two")
        file.should_receive(:puts).with("six")
       
        get 'test'
   
    end
   

    it "does pass" do
   
        file = mock('file')
        File.stub!(:new).and_return(file)
       
        file.should_receive(:puts).with("one")
        file.should_receive(:puts).with("two")
        file.should_receive(:puts).with("six")
        file.should_not_receive(:puts).with("ten")
       
        get 'test'
   
    end

end

----

The first example fails with error message "Mock 'file' expected :puts 
with ("one") but received it with ("three")" (The message seems a little 
strange since "one" is clearly received, but I can live with that. I 
understand the point Steve made that a mock should have all messages 
specified in expectations).

The second example passes fine, which is the thing I still find 
surprising. It seems as if "should_not_receive" doesn't just match the 
absence of the specified message but also the presence of any message 
other than the specified message.

Mark.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://rubyforge.org/pipermail/rspec-users/attachments/20081023/b67ce0f4/attachment-0001.html>


More information about the rspec-users mailing list