# frozen_string_literal: true require 'rails_helper' RSpec.describe CreatePokemonFromBase64Service, type: :service do describe '#execute' do let(:service) { described_class.new } subject { service.execute(encoded_pokemon) } let(:encoded_pokemon) { '1234567890abcdef' } let(:client_response) { double(pokemon: [pokemon]) } let(:pokemon) do pkmn = {pokedex_number: 10, nickname: 'pyukuchu'} double(**pkmn, to_h: pkmn) end before do allow_any_instance_of(PKParse::Client).to receive(:parse_base64).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) end it 'calls #error' do expect(service).not_to receive(:success) expect(service).to receive(:error) subject rescue nil end end context 'committing result to database succeeds' do before do allow_any_instance_of(PKParse::Client).to receive(:parse_base64).and_return(client_response) end it 'creates some new pokemon' do expect { subject }.to change { Pokemon.count }.by(1) end it 'calls #success' do expect(service).to receive(:success).once expect(service).not_to receive(:error) subject end end end context 'parsing fails' do before do allow_any_instance_of(PKParse::Client).to( receive(:parse_base64).and_raise(PKParse::Error.new(StandardError.new)), ) end it 'does not create any new pokemon' do expect(service).not_to receive(:success) expect(service).to receive(:error) expect { subject }.to change { Pokemon.count }.by(0) end end context '#success' do it 'calls super method' do allow_any_instance_of(PKParse::Client).to receive(:parse_base64).and_return(client_response) expect(service).to receive(:success).once expect_any_instance_of(service.class.superclass).to receive(:success).once subject end end end end