Forum: Ruby RSpec question about catching expected exception in class .new

Posted by tamouse mailing lists (Guest)
on 2012-11-09 15:01
(Received via mailing list)
I have the following I'm trying to test:

  class Marker
    def initialize(secret, guess)
      raise ArgumentError, "secret and guess must be the same length",
caller if guess.length != secret.length
      @secret, @guess = secret, guess
    end

   ...


In my spec test, how do I capture that exception? I'm trying to test
that it raises appropriately when secret and guess are different
lengths.

What I've tried:

      context "unequal lengths" do
        it 'returns "secret and guess must be the same length"' do
          Marker.new('1234','').should raise_error("secret and guess
must be the same length")
        end
      end

But it doesn't actually catch the error, calling it a failed test.
I've also tried raise_error(ArgumentError) with the same result. (I've
also tried calling Maker::new, but that also has the same result.
Posted by Kaspar Schiess (kaspar)
on 2012-11-09 17:59
(Received via mailing list)
On 09.11.12 15:01, tamouse mailing lists wrote:
>       context "unequal lengths" do
>         it 'returns "secret and guess must be the same length"' do
>           Marker.new('1234','').should raise_error("secret and guess
> must be the same length")
>         end
>       end

Try something like this:

    context "unequal lengths" do
      it 'returns "secret and guess must be the same length"' do
        expect {
          Marker.new('1234','')
        }.to raise_error("secret and guess must be the same length")
      end
    end

That should do the trick.
k
Posted by tamouse mailing lists (Guest)
on 2012-11-10 03:04
(Received via mailing list)
On Fri, Nov 9, 2012 at 10:59 AM, Kaspar Schiess <eule@space.ch> wrote:
>     context "unequal lengths" do
>
Oh, thanks, yes! I guess I didn't read far enough in the RSpec book; I 
found it!
Please log in before posting. Registration is free and takes only a minute.
Existing account (Switch to SSL-encrypted connection)
NEW: Do you have a Google/GoogleMail or Yahoo account? No registration required!
Log in with Google account | Log in with Yahoo account
No account? Register here.