Skip to content

Instantly share code, notes, and snippets.

@tombh
Created January 6, 2016 23:29
Show Gist options
  • Save tombh/7d9fa9ff4cbcded17c2a to your computer and use it in GitHub Desktop.
Save tombh/7d9fa9ff4cbcded17c2a to your computer and use it in GitHub Desktop.
class ErrorHandler
def foo
potential_error
rescue StandardError
puts 'An error was handled'
end
end
RSpec.describe do
let(:instance) { ErrorHandler.new }
example 'raising then not raising an exception' do
allow(instance).to receive(:potential_error).and_raise StandardError
allow(instance).to receive(:potential_error).and_return true
expect(instance).to receive(:puts)
instance.foo
instance.foo
end
end
# Failures:
# 1) raising then not raising an exception
# Failure/Error: expect(instance).to receive(:puts)
# (#<ErrorHandler:0x00560c41e27400>).puts(*(any args))
# expected: 1 time with any arguments
# received: 0 times with any arguments
# # ./rspec.rb:15:in `block (2 levels) in <top (required)>'
# Finished in 0.00458 seconds (files took 0.09087 seconds to load)
# 1 example, 1 failure
@myronmarston
Copy link

Sorry for leading you astray :(. You can achieve this by passing a block:

raise_error = true
allow(instance).to receive(:potential_error) do
  if raise_error
    raise_error = false
    raise "boom"
  end

  true
end

@tombh
Copy link
Author

tombh commented Jan 7, 2016

Ah yes, perfect! Thank you :)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment