2012-06-12 12 views
14

Próbuję przetestować gałąź kontrolera Rails, która jest uruchamiana, gdy metoda modelu powoduje błąd.Jak mogę uruchomić metodę zgłaszania błędu za pomocą Ruby MiniTest?

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 

Jak mogę uzyskać minimalistyczny stub, aby podnieść ten błąd?

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 

Odpowiedz

10

Jednym ze sposobów jest użycie Mocha, które domyślnie ładuje Railsy.

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 
+0

Jeśli wyjątek ma argumentów, trzeba dostarczyć instancję: '' 'MyObject.any_instance.expects (: my_model_method) .raises (Wyjątki :: CustomError.new (some_arg))' '' – Tony

14
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 
+11

Wskazówka dla profesjonalistów: Jeśli metoda, którą chcesz wywołać, ma wyjątek, musisz uwzględnić te w swoim lambda: raises_exception = -> (a, b, c) {raise ArgumentError.new}. – Brad

+0

To działa dla mnie i powinno być, IMO, być przyjętą odpowiedzią. – egeland

Powiązane problemy