[rspec-users] [JRuby] simulating a java exception in a spec

Lenny Marks lenny at aps.org
Mon Aug 22 17:50:10 EDT 2011

JRuby 1.6.2
rspec-core (2.6.4)
rspec-expectations (2.6.0)
rspec-mocks (2.6.0)
rspec-rails (2.6.1)

I'm sure this has more to do with the way JRuby wraps Java exceptions but I figured I'd post here in case anyone here has any insight or pointers. In the context of writing a spec for a model like thing that wraps legacy Java code, I found myself attempting to stub a method on a Java Exception rescued in the implementation.


describe '#valid?' do
it 'adds validation exceptions raised by service to #errors' do
      ve = ValidationException #a java exception
      ve.stub(:localized_message).and_return('a bunch of errors')



      subject.errors.should == ['a bunch of errors']

the above example fails because the :localize_message stub is ignored and instead the real implementation receives the message. I know this typically screams typo but not in this case. Here is a more boiled down version:

specify 'rescued exception message should be "bar" because I stubbed it' do
        e = Java::java.lang.NullPointerException.new('foo')
        raise e
      rescue Java::java.lang.NullPointerException => e
        e.message.should == 'bar'

Failure/Error: e.message.should == 'bar'
       expected: "bar"
            got: "foo" (using ==)

That seemed odd to me but maybe moot anyway since in reality I would be need to rescue a NativeException masquerading as my target exception.

e.g. This code

def valid?
    rescue ValidationException => e
      puts "rescued exception: #{e.class.name}"

prints "rescued exception: NativeException"  when hit through the console.

So how would one simulate a NativeException if needed (i.e. you want to stub methods on it)?


More information about the rspec-users mailing list