How to test side effect of the method which raises error

时间:2015-11-12 10:43:32

标签: ruby-on-rails ruby testing rspec

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 user is created. Is there any other ways to do it?

2 个答案:

答案 0 :(得分:3)

也许是这样的:

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

答案 1 :(得分:1)

这可能会这样做:

expect { method }.to raise_error(StandardError)
expect { method rescue 'method rescued' }.to eq('method rescued')
expect { method rescue 'method rescued' }.not_to change { User.count }