[mocha-developer] Stubbing objects and calling to_json on them errors (circular reference)

John Wilger johnwilger at gmail.com
Mon Oct 20 14:01:57 EDT 2008


On Oct 20, 2008, at 8:14 AM, Bill Kocik wrote:

> Suppose you have a controller action like this:
>
> def do_something
>  @something = Something.find(:first)
>  @something.do_whatever
>  render :json => @something.to_json
> end
>
> A test might be this:
>
> context "when do_something is called" do
>  setup do
>    @something = Something.new()
>    Something.expects(:find).returns(@something)
>    @something.stubs(:do_whatever)
>    get :do_something
>  end
>  should_respond_with :success
> end
>
> Because I stubbed a method on my @something object (and this also  
> happens with expects()), I get this:
>
> 1) Error:
> test: when do_something is called should respond with success.  
> (SomethingControllerTest):
> ActiveSupport::JSON::CircularReferenceError: object references itself

Hi Bill,

I would suggest not using an actual instance of Something at all. You  
are testing SomethingController, not Something—and you are already  
using mocking/stubbing—so why not just have:

     context "when do_something is called" do
       setup do
         something = stub_everything
         Something.stubs(:find).returns(something)
         get :do_something
       end
       should_respond_with :success
     end

-- 
Regards,

John Wilger


More information about the mocha-developer mailing list