How to Raise an Exception in an Rspec Test

How to raise an exception in an RSpec test

Like this, for example

expect(object).to receive(:save).and_raise(ActiveRecord::StaleObjectError)

Rspec: How to test a method that raises an error

You should be able to use Rspec compound expectations for this

https://relishapp.com/rspec/rspec-expectations/docs/compound-expectations

So I'll re-write your expectation to something like this:

expect { handler.call }.
to raise_error(FailedPaymentError).
and change { Subscription.count }.by(1)

Rspec: How to test an exception is raised in private method?

try and_raise(Product::StaleObjectError.new(nil, nil))

see this question i asked a while about the same issue:

Rspec - wrong number of arguments when raising error

How to raise standard error from a rspec test?

This is correct spec. You should use {} (block brackets) since you are waiting for it to raise error. Simple brackets that you have use are for values checking.

context '#validate(test_tool)' do
it { expect{test_tool.validate}.to raise_error StandardError }

How do I `expect` something which raises exception in RSpec?

You could use the "rescue nil" idiom to shorten what you already have:

it { expect { eat(what: nil) rescue nil }.not_to change(cat, :status) }


Related Topics



Leave a reply



Submit