Search code examples
rubyrspec

rspec: raise_error usage to match error message


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.


Solution

  • 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.