Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

rspec: raise_error usage to match error message

Tags:

ruby

rspec

I raised an error using raise(ConfigurationError.new(msg))

I tried to test this with rspec:

expect {
  Base.configuration.username
}.to raise_error(ConfigurationError, message) 

But this doesn't work. How can I test this? The goal is to match message.

like image 294
user1291365 Avatar asked Aug 06 '13 13:08

user1291365


2 Answers

You can match error message with regex:

it { expect{ Foo.bar }.to raise_error(NoMethodError, /private/) }

This will check if NoMethodError raised with private method message not undefined method.

Will be useful because NoMethodError.new didn't pass tests even with same error message.

like image 164
Artem P Avatar answered Oct 31 '22 05:10

Artem P


Make sure you are using rspec > 2.14.0 and take a look at this commit:

https://github.com/rspec/rspec-expectations/commit/7f02b503d5ae48d1141b6465acd0a7a4e1bb84dd

it "passes if an error instance is expected" do
  s = StandardError.new
  expect {raise s}.to raise_error(s)
end
like image 22
neojin Avatar answered Oct 31 '22 03:10

neojin