How do I stub a method to raise an error using Ruby MiniTest?
require "minitest/autorun"class MyModel def my_method; endendclass TestRaiseException < MiniTest::Unit::TestCase def test_raise_exception model = MyModel.new raises_exception = -> { raise ArgumentError.new } model.stub :my_method, raises_exception do assert_raises(ArgumentError) { model.my_method } end endend
One way to do this is to use Mocha, which Rails loads by default.
it 'should show redirect on custom error' do my_object = FactoryGirl.create(:my_object) # stub my_model_method to raise Exceptions::CustomError here MyObject.any_instance.expects(:my_model_method).raises(Exceptions::CustomError) post :my_controller_method, :id => my_object.to_param assert_response :redirect assert_redirected_to my_object_path(my_object) flash[:error].wont_be_nilend