How do I stub a method to raise an error using Ruby MiniTest?

家住魔仙堡 提交于 2021-02-07 11:13:57

问题


I'm trying to test a Rails controller branch that is triggered when the model method raises an error.

def my_controller_method
  @my_object = MyObject.find(params[:id])

  begin
    result = @my_object.my_model_method(params)
  rescue Exceptions::CustomError => e
    flash.now[:error] = e.message       
    redirect_to my_object_path(@my_object) and return
  end

  # ... rest irrelevant
end

How can I get a Minitest stub to raise this Error?

it 'should show redirect on custom error' do
  my_object = FactoryGirl.create(:my_object)

  # stub my_model_method to raise Exceptions::CustomError here

  post :my_controller_method, :id => my_object.to_param
  assert_response :redirect
  assert_redirected_to my_object_path(my_object)
  flash[:error].wont_be_nil
end

回答1:


require "minitest/autorun"

class MyModel
  def my_method; end
end

class 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
  end
end



回答2:


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_nil
end


来源:https://stackoverflow.com/questions/10990622/how-do-i-stub-a-method-to-raise-an-error-using-ruby-minitest

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!