Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I check if my subject raises an exception?

Tags:

ruby

rspec

rspec3

I'm currently creating an object in subject and need to test if this raises an exception. The following code illustrates what I'm trying to achieve:

describe MyClass do
  describe '#initialize' do
    subject { MyClass.new }

    it { is_expected.not_to raise_error(Some::Error) }
  end
end

I have a feeling I'm going about this the wrong way. What is the preferred way to set the subject to a new object, without creating the object twice?


Update

My problem was two-fold. Firstly, this syntax does not work:

it { is_expected.not_to raise_error }

Using expect inside an it block does, however (as pointed out by Jimmy Cuadra):

it 'does not raise an error' do
  expect { subject }.not_to raise_error
end

I am not well enough acquainted with RSpec to tell you why this is.

Secondly, since RSpec 3.0.0.beta1, it is longer possible to use raise_error with a specific error class. The following, therefore, is invalid:

expect { subject }.to raise_error(Some::Error)

For more information, see

  • Rspec 3.0.0.beta1 changelog
  • Consider deprecating `expect { }.not_to raise_error(SpecificErrorClass)` #231
  • Remove expect {}.not_to raise_error(SomeSpecificClass) #294
like image 907
Jamie Schembri Avatar asked Jul 27 '14 18:07

Jamie Schembri


People also ask

How do I check if an exception is raised in Python?

There are two ways you can use assertRaises: using keyword arguments. Just pass the exception, the callable function and the parameters of the callable function as keyword arguments that will elicit the exception. Make a function call that should raise the exception with a context.

What does raising an exception mean?

Raising an exception is a technique for interrupting the normal flow of execution in a program, signaling that some exceptional circumstance has arisen, and returning directly to an enclosing part of the program that was designated to react to that circumstance.

Why would you raise an exception in your code?

Errors come in two forms: syntax errors and exceptions. While syntax errors occur when Python can't parse a line of code, raising exceptions allows us to distinguish between regular events and something exceptional, such as errors (e.g. dividing by zero) or something you might not expect to handle.

What is the syntax for raising an exception?

The raise keyword is used to raise an exception. You can define what kind of error to raise, and the text to print to the user.


1 Answers

If I'm understanding correctly, you're trying to test if instantiating a class causes an exception. You would just do this:

describe MyClass do
  it "doesn't raise an exception when instantiated" do
    expect { subject }.not_to raise_error
  end
end 
like image 142
Jimmy Avatar answered Oct 07 '22 00:10

Jimmy