[mocha-developer] [Rails] Trying to Overide Class Object Methdos For Testing

James Mead jamesmead44 at gmail.com
Tue Aug 15 19:34:02 EDT 2006


On 15/08/06, Steven Hansen <runner at berkeley.edu> wrote:
>
> Ok, this does what I was trying to accomplish:
>
> class ValidationMaster
>   def validate(params)
>     # complex and time consuming validation
>     # returns true on success, raises Exception
>     # on failure
>   end
> end
>
> def test_validation_fails
>    ValidationMaster.class_eval { def validate(params); raise Exception;
> end }
>
>    post(:download, opts)
>    assert_response(:redirect)
>    assert_equal(flash[:error], "Authentication failed: token
> verification failed")
> end
>
> def test_validation_succeeds
>    ValidationMaster.class_eval { def validate(params); return true; end }
>    post(:download, opts)
>    assert_response(:success)
>    assert_equal(flash[:error], nil)
> end
>
>
> I don't want the actual validation to run, I just want a specific result
> from this method.  The result I want differs between tests.  Now I can
> test my controller's actions without having to have the "real"
> validation() method executed.  Sorry for not giving a better explanation
> of what I was trying to do.


That does work, but watch out for the gotcha that your method re-definition
is not local to the test. So depending on which was the last of these to
run, the behaviour in other tests might not be what you expect. This is one
of the benefits of Mocha, which restores the original implementation after
each test (in a secret teardown). Your tests would become...

def test_validation_fails
   ValidationMaster.any_instance.stubs(:validate).raises(Exception)
   post(:download, opts)
   assert_response(:redirect)
   assert_equal(flash[:error], "Authentication failed: token verification
failed")
end

def test_validation_succeeds
   ValidationMaster.any_instance.stubs(:validate).returns(true)
   post(:download, opts)
   assert_response(:success)
   assert_equal(flash[:error], nil)
end

James.
http://blog.floehopper.org
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://rubyforge.org/pipermail/mocha-developer/attachments/20060816/5d49abcd/attachment-0001.html 


More information about the mocha-developer mailing list