[mocha-developer] [Rails] Trying to Overide Class Object Methdos For Testing
James Mead
jamesmead44 at gmail.com
Tue Aug 15 16:41:45 EDT 2006
On 15/08/06, Steven Hansen <runner at berkeley.edu> wrote:
>
> I thought I had a handle on the whole singleton class thing but now I'm
> not too sure.
>
> I have a class definition:
>
> class ValidationMaster
> def validate(params)
> # complex and time consuming validation
> # returns true on success, raises Exception
> # on failure
> end
> end
>
> Okay, so when I'm running my functional tests within rails, I want to be
> able to control how the validate(params) method behaves.
>
> So, I've created a ValidationMaster class definition and put it in
> RAILS_ROOT/test/mocks/test/validation_master.rb
>
> The methods I've defined there seem to be correctly overriding those of
> the original class definition.
>
> Now here is where I'm having problems. Within certain functional tests,
> I want validate(params) to return true. Other times
> I want it to fail and throw an exception. Thus, I can't rely on the
> Mock ValidationMaster class definition to take care of this.
>
> But then I thought, HEY, within each test I can open up the singleton
> class for the ValidationMaster class object. Whoo hoo,
> I'm in charge now!
>
> def test_stuff
> class << ValidationMaster
> def validate(params)
> raise ValidationException
> end
> end
>
> vm = ValidationMaster.new
> vm.validate("Jeff")
> end
>
> But, when I run my test, the exception is not getting thrown. The
> methods I've defined in the Mock are all working right, but it's somehow
> not seeing
> the override within test_stuff. Am I mistaken here, can I not override
> the class definition of ValidationMaster like this?
I think this is what you want...
def test_stuff
vm = ValidationMaster.new
class << vm
def validate(params)
raise ValidationException
end
end
vm.validate("Jeff")
end
However, you might want to consider using Mocha
<http://mocha.rubyforge.org>to write the test more concisely...
def test_stuff
vm = ValidationMaster.new
vm.stubs(:validate).raises(ValidationException)
vm.validate("Jeff")
end
Hope that helps.
James.
http://blog.floehopper.org
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://rubyforge.org/pipermail/mocha-developer/attachments/20060815/5fd5ce9e/attachment.html
More information about the mocha-developer
mailing list