[mocha-developer] Using any_instance with Rails to make sure the right thing is saved?

James Mead jamesmead44 at gmail.com
Tue Feb 6 13:57:05 EST 2007


On 06/02/07, James Moore <jamesthepiper at gmail.com> wrote:
>
> I'd like to test that an object with the correct attributes is saved,
> something like:
>
>   def test_create_without_existing_suite
>     this = self
>     w = Annotation.any_instance.expects(:save).with do |x|
>       this.assert_equal 'fnord',
> some_way_get_the_name_of_the_receiver_of_save
>       true
>     end
>     w.returns true
>   end
>
> But the object is created inside the method being tested (in this case, a
> test of a Rails controller's 'create' method), so
> I don't think there's a way to just mock the method on the particular
> object.
>
> Is there a way to get the target of the mocked method from inside
> any_instance?
>
> Or am I going about this the wrong way?  Is there a way to be notified
> when
> new instances of a class are created, and then do something like
> automatically mock some of their methods?
>

You can stub the 'new' or 'create' methods of a class and return a mock
object.

So you'd have something along these lines in your test...

  annotation = mock('annotation')
  annotation.expects(:update_attributes).with(:name =>
'wibble').returns(true)
  Annotation.stubs(:new).returns(new_annotation)
  post :create, :name => 'wibble'

-- 
James.
http://blog.floehopper.org


More information about the mocha-developer mailing list