2013-12-23 30 views
0

我遇到了匹配器捕捉異常的麻煩。控制器方法只是做一個REST調用,並得到與id的水果,我想測試當REST給我一個錯誤響應,在rails中是JSON :: ParserError。我想測試這種情況,所以我將REST調用存根並引發異常。rails rspec匹配異常與存根方法

我知道這個事實,因爲我得到了確切的錯誤,樁工作。我相信,我只是需要一個匹配捕獲錯誤調用得到

In Controller 

def show 
    @fruit = FruitsService::Client.get_fruit(params[:id]) 
end 

規格/控制器/ fruits_controller_spec.rb

describe '#show' do 
    before do  
    context 'when a wrong id is given' do 
     FruitsService::Client.any_instance 
      .stub(:get_fruit).with('wrong_id') 
      .and_raise(JSON::ParserError) 
    end 

    it 'receives 404 error code' do 
    get :show, {id: 'wrong_id'} <------ I think I might need a matcher for this ? 
    expect(FruitsService::Client.get_fruit('wrong_id')).to raise_error(JSON::ParserError) 
    end 

end 

這給這個

Failure/Error: get :show, {id: 'wrong_id'} 
JSON::ParserError: 
    JSON::ParserError 

回答

3

當你想要的時候要測試行爲,如發生錯誤,則需要將塊傳遞給expect而不是參數,如下所示:

it 'receives 404 error code' do 
    expect { get :show, {id: 'wrong_id'} }.to raise_error(JSON::ParserError) 
end