# Stubbing method which adds error to model

**URL:** <https://www.ruby-forum.com/t/stubbing-method-which-adds-error-to-model/134505>\
**Category:** Rails\
**Created:** [April 11, 2008, 3:09pm UTC](https://www.ruby-forum.com/t/stubbing-method-which-adds-error-to-model/134505 "2008-04-11T15:09:17Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![vincesf](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/v/6bbea6/32.png) [@vincesf](https://www.ruby-forum.com/u/vincesf)\
**Post date:** [April 11, 2008, 3:09pm UTC](https://www.ruby-forum.com/t/stubbing-method-which-adds-error-to-model/134505/1 "2008-04-11T15:09:17Z")

</div>

Hi,

I’m trying to stub a method for a model. Although I’m making it work I  
can’t find the best way to do it. This method is supposed to add an  
error to my instance.

class User \< ActiveRecord::Base  
def my\_special\_method

# … do somwthing before

errors.add(:name, “wrong name”)  
end

class UserTest \< Test::Unit::TestCase  
def test\_with\_error  
u = User.new  
User.any\_instance.stubs(:my\_special\_method).returns(lambda  
{u.errors.add(:name, “wrong name”)})  
foo = User.new  
foo.my\_my\_special\_method  
pp foo.errors # \<= works  
foo = User.new default\_user  
foo.my\_special\_method  
pp foo.valid?  
pp foo.errors # \<= still works  
end

Only issue with this code is that it throws a warning from Mocha telling  
me that lambda is deprecated. I can’t find a way to make it works in any  
other way though.  
def test\_with\_error\_case2  
u = User.new  
User.any\_instance.stubs(:my\_special\_method).returns(u.errors.add(:name,  
“wrong name”))  
foo = User.new  
foo.my\_special\_method  
pp foo.errors # \<= can see the error  
foo.valid?  
foo.my\_special\_method  
pp foo #\<= no error has been set  
end  
Adding times(n) to the stubs doesn’t help me.

Thank you for your help as I’m clearly missing something here

Vince

---

<div class="post-metadata">

**Author:** ![vincesf](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/v/6bbea6/32.png) [@vincesf](https://www.ruby-forum.com/u/vincesf)\
**Post date:** [April 11, 2008, 3:25pm UTC](https://www.ruby-forum.com/t/stubbing-method-which-adds-error-to-model/134505/2 "2008-04-11T15:25:38Z")

</div>

On 11 Apr 2008, at 14:09, V. Vincesf wrote:

> foo.my\_special\_method  
> pp foo.valid?  
> pp foo.errors # \<= still works  
> end
> 
> Only issue with this code is that it throws a warning from Mocha  
> telling  
> me that lambda is deprecated. I can’t find a way to make it works in  
> any  
> other way though.

in your lambda, you are referencing u, so when you call  
my\_special\_method on foo, it is still adding the errors to u.  
Fundamentally though stubs aren’t really suppose to do anything,  
whereas you are trying to make them do something.

Fred
