I'm trying to test a Rails controller branch that is triggered when the model method raises an error.
我正在测试一个Rails控制器分支,该分支在模型方法引发错误时被触发。
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
2 个解决方案
#1
16
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
10
One way to do this is to use Mocha, which Rails loads by default.
一种方法是使用Mocha,这是Rails默认加载的。
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
#1
16
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
10
One way to do this is to use Mocha, which Rails loads by default.
一种方法是使用Mocha,这是Rails默认加载的。
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