# frozen_string_literal: true require 'rails_helper' RSpec.describe API::V1::PokemonController, type: :controller do def non_existant_pokemon_id(initial_id = 1) id = initial_id id *= 2 while Pokemon.find_by(id: id) id end describe 'DELETE #destroy' do let!(:pokemon) { FactoryBot.create(:pokemon) } subject { delete :destroy, params: {id: pokemon.id} } context 'the pokemon is successfully deleted' do it 'deletes the pokemon' do expect{subject}.to change{Pokemon.count}.by(-1) expect(response).to render_template 'api/v1/pokemon/show' end end context 'the pokemon is not deleted' do before { allow_any_instance_of(Pokemon).to receive(:destroy).and_return(false) } it 'does not delete the pokemon' do expect{subject}.to change{Pokemon.count}.by(0) expect(response).to render_template 'api/v1/application/_error' end end context 'the pokemon does not exist' do let(:pokemon) { double(id: non_existant_pokemon_id) } it 'raises an error' do expect{subject rescue nil}.to change{Pokemon.count}.by(0) expect(response).to render_template 'api/v1/application/_error' end end end describe 'POST #upload' do subject { post :upload, params: {pokemon: double} } let(:client_response) { double(pokemon: [pokemon]) } let(:pokemon) do double(pokedex_number: 10, nickname: 'pyukuchu', to_h: {pokedex_number: 10, nickname: 'pyukuchu'}) end before do allow_any_instance_of(PKParse::Client).to receive(:parse).and_return(client_response) end context 'parsing succeeds' do context 'committing result to database fails' do before { allow(Pokemon).to receive(:create!).and_raise(ActiveRecord::ActiveRecordError.new) } it 'does not create any new pokemon' do # expect{subject}.to raise_error 'canned failure' expect{(subject rescue nil)}.to change{Pokemon.count}.by(0) expect(response).to render_template 'api/v1/application/_error' end end context 'committing result to database succeeds' do before do allow_any_instance_of(PKParse::Client).to receive(:parse).and_return(client_response) end it 'creates some new pokemon' do expect{subject}.to change{Pokemon.count}.by(1) expect(response).to render_template 'api/v1/pokemon/index' end end end context 'parsing fails' do before do allow_any_instance_of(PKParse::Client).to receive(:parse).and_raise(PKParse::Error.new(StandardError.new)) end it 'does not create any new pokemon' do expect{subject}.to change{Pokemon.count}.by(0) expect(response).to render_template 'api/v1/application/_error' end end end describe 'GET #show' do context 'the pokemon exists' do let!(:pokemon) { FactoryBot.create(:pokemon) } subject { get :show, params: {id: pokemon.id}, format: :json } it 'renders the pokemon JSON' do subject expect(response).to render_template 'api/v1/pokemon/show' end end end end