Search code examples
ruby-on-railsrubytestingrspec

How to test side effect of the method which raises error


I have a method like:

def method
  # ..
  begin
    some_invokation
  rescue StandardError
    # some_other_stuff
    raise
  end
  # ..
  User.create!
end

Right now I can test that this method raises the exception:

expect { method }.to raise_error(StandardError)

But also I would like to test that the user is not created.

expect { method }.not_to change { User.count }

It doesn't work. It shows that the exception was raised. I tried to mock raise invocation:

allow_any_instance_of(described_class).to receive(:raise)

But in this case my method is not interrupted and the user is created. Are there any other ways to do it?


Solution

  • Perhaps something like:

    expect { 
      method rescue nil
    }.not_to change { User.count }