Stubbing method which adds error to model

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

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