Skip to content

Instantly share code, notes, and snippets.

@tcnksm
Created November 12, 2013 08:20
Show Gist options
  • Save tcnksm/7427400 to your computer and use it in GitHub Desktop.
Save tcnksm/7427400 to your computer and use it in GitHub Desktop.
How to stub raising exceptions in rspec
class Foo
class << self
def exec
something
rescue => ex
ex.message
end
def something
"something"
end
end
end
describe Foo do
describe ".exec()" do
context "when error occured" do
before do
Foo.stub(:something).and_raise(StandardError.new("error"))
end
subject(:msg) { Foo.exec }
it "returns its error message" do
expect(msg).to eq("error")
end
end
end
end
@kubakrzempek
Copy link

In case anybody would be interested in how to stub that in today's world of rspec:

before do
  allow(Foo).to receive(:something).and_raise(StandardError.new("error"))
end

Cheers!

@Ricardonacif
Copy link

Ricardonacif commented Jun 10, 2020

In case anybody would be interested in how to stub that in today's world of rspec:

before do
  expect(Foo).to receive(:something).and_raise(StandardError.new("error"))
end

Greetings from 2020 (yeah, THAT year).

@jeanmw
Copy link

jeanmw commented Jan 26, 2021

and_raise(StandardError.new("error"))

haha, nice thank you :)

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