2013-12-20 64 views
0

我想爲我的控制器之一編寫一些rspec聯合測試,並且我正在運行int有關stubbing REST api調用的一點疑惑。rails rspec存根並提出響應代碼404響應

所以我有這個REST調用哪個接收水果ID並返回一個特定的水果信息,我想測試何時REST給我回應代碼404(未找到)。理想情況下,我會踩滅的方法調用和返回錯誤代碼

在控制器

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     <----------- I think this is my problem 

    get :show, {id: 'wrong_id'} 
    end 

    it 'receives 404 error code' do 
    expect(response.code).to eq('404') 
    end 

end 

這給這個

Failure/Error: get :show, {id: 'wrong_id'} 
RuntimeError: 
    RuntimeError 
+0

您的測試出您磕碰 – bjhaid

回答

0

您沒有處理控制器中的響應。我不確定你的API在404情況下返回什麼。如果它只是引發異常,那麼你將不得不修改你的代碼並測試一下。假設你有一個索引行動

def show 
    @fruit = FruitsService::Client.get_fruit(params[:id]) 
rescue Exception => e 
    flash[:error] = "Fruit not found" 
    render :template => "index" 
end 

describe '#show' do 
    it 'receives 404 error code' do 
    FruitsService::Client.stub(:get_fruit).with('wrong_id').and_raise(JSON::ParserError) 

    get :show, {id: 'wrong_id'} 

    flash[:error].should == "Fruit not found" 
    response.should render_template("index") 
    end 

end 
+0

我剛剛發現的REST API調用實際上將拋出一個WebapplicationException,它會返回一個JSON字符串「提供的水果ID爲背景的如果id不存在,則爲'null'。我正在考慮是否存在殘留並引發異常 – AirWick219

+0

Rails將通過WebApplicationException的另一種異常類型來處理異常。打印救援塊內的'e.class'以找出異常類型,並在測試 – usha

+0

中提出相同的異常,結果發現它是JSON :: ParserError,所以我猜想我的原始想法與FruitsService :: Client。 any_instance.stub(:get_fruit).with('wrong_id')。and_raise(JSON :: ParserError) – AirWick219