1
votes

I am trying to write some rspec unite test for one of my controller and I am running int a little confusion about stubbing a REST api call.

so I have this REST call which take the fruit id and return a particular fruit information and I want to test when REST give me respond code 404 (Not Found). Ideally, I would stub out the method call and return the error code

In Controller

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

spec/controller/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 

This giving this

Failure/Error: get :show, {id: 'wrong_id'}
 RuntimeError:
   RuntimeError
1
your test is out of the Context that you are stubbingbjhaid

1 Answers

0
votes

you are not handling the response in your controller. I am not sure what your API returns in case of 404. If it just raises an exception, then you will have to modify your code and test a little bit. Assuming you have an index action

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