如何使用Ruby MiniTest存根一个引发错误的方法?
我正在尝试测试一个Rails控制器分支,该分支在model方法引发错误时被触发如何使用Ruby MiniTest存根一个引发错误的方法?,ruby,minitest,Ruby,Minitest,我正在尝试测试一个Rails控制器分支,该分支在model方法引发错误时被触发 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
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
我如何获得一个小型测试存根来引发此错误
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
一种方法是使用Mocha,Rails默认加载Mocha
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
要求“小型测试/自动运行”
类MyModel
定义我的方法;结束
结束
类TestRaiseException{raise ArgumentError.new}
model.stub:my_方法,引发_异常do
assert_引发(ArgumentError){model.my_method}
结束
结束
结束
Pro提示:如果要存根以引发异常的方法具有参数,则需要在lambda中包含这些参数:raises_exception=->(a,b,c){raise ArgumentError.new}。如果异常具有参数,则必须提供实例:MyObject.any_instance.expected(:my_model_method)。引发(Exceptions::CustomError.new(some_arg))
@Tony你救了我一天!这个评论应该会得到很多支持。你也可以直接在实例上存根期望,而不是存根MyObject的“any_instance”。只需直接调用my_对象实例上的expects。