Rails ActiveSupport: how to claim that an error occurs?

I want to test a function on one of my models that causes certain errors. The function looks something like this:

def merge(release_to_delete) raise "Can't merge a release with itself!" if( self.id == release_to_delete.id ) raise "Can only merge releases by the same artist" if( self.artist != release_to_delete.artist ) #actual merge code here end 

Now I want to say that when I call this function with a parameter that raises each of these exceptions, that the exceptions actually get thrown. I looked at ActiveSupport documentation, but I did not find anything promising. Any ideas?

+36
ruby-on-rails assert raise activesupport
Aug 11 '10 at 2:47
source share
2 answers

Thus, unit testing is indeed not supported by assets. Ruby comes with a typical xunit framework in standard libs (Test :: Unit in ruby ​​1.8.x, MiniTest in ruby ​​1.9), and the stuff in activesupport just adds a few things to it.

If you use Test :: Unit / MiniTest

 assert_raises(Exception) { whatever.merge } 

if you use rspec (unfortunately poorly documented, but more popular)

 lambda { whatever.merge }.should raise_error 

If you want to check the raised Exception :

 exception = assert_raises(Exception) { whatever.merge } assert_equal( "message", exception.message ) 
+82
Aug 11 '10 at 2:54
source share

To verify that the exception was not thrown (or successfully processed), run inside your test case:

 assert_nothing_raised RuntimeError do whatever.merge end 

To verify that an error is occurring, run inside your test case:

  assert_raise RuntimeError do whatever.merge end 

Yes, it's that simple! :)

+8
Dec 04 '13 at 5:32
source share



All Articles