user1993565 user1993565 - 2 months ago 22
Ruby Question

RSpec with my custom error class

In RSPec I have this:

expect{obj.my_method}.to raise_error(Module::Error::MyErrorClass)


and my test is failing with following:

expected Module::Error::MyErrorClass, got #<RuntimeError: My error message.


I want something like

expect{obj.my_method}.to raise_error(Module::Error::MyErrorClass.message)


but in that case test just fails without any particular message. How can I make it pass?

My error class looks like:

module Module
module Error
class MyErrorClass < StandardError
def self.message
raise "My error message."
end
end
end
end

Answer

Your error class's message method should simply define a string - i.e.

module Module
  module Error
    class MyErrorClass < StandardError
      def message
        "My error message."
      end
    end
  end
end

Now, assuming this exception is actually getting raised, any of the following should work:

expect{obj.my_method}.to raise_error(Module::Error::MyErrorClass)
expect{obj.my_method}.to raise_error(Module::Error::MyErrorClass.new.message)
expect{obj.my_method}.to raise_error("My error message.")
expect{obj.my_method}.to raise_error(Module::Error::MyErrorClass, "My error message.")

(Link to RSpec docs for this matcher.)

Comments