create_pokemon_from_base64_service_spec.rb 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. # frozen_string_literal: true
  2. require 'rails_helper'
  3. RSpec.describe CreatePokemonFromBase64Service, type: :service do
  4. describe '#execute' do
  5. let(:service) { described_class.new }
  6. subject { service.execute(encoded_pokemon) }
  7. let(:encoded_pokemon) { '1234567890abcdef' }
  8. let(:client_response) { double(pokemon: [pokemon]) }
  9. let(:pokemon) do
  10. pkmn = {pokedex_number: 10, nickname: 'pyukuchu'}
  11. double(**pkmn, to_h: pkmn)
  12. end
  13. before do
  14. allow_any_instance_of(PKParse::Client).to receive(:parse_base64).and_return(client_response)
  15. end
  16. context 'parsing succeeds' do
  17. context 'committing result to database fails' do
  18. before { allow(Pokemon).to receive(:create!).and_raise(ActiveRecord::ActiveRecordError.new) }
  19. it 'does not create any new pokemon' do
  20. # expect{subject}.to raise_error 'canned failure'
  21. expect { (subject rescue nil) }.to change { Pokemon.count }.by(0)
  22. end
  23. it 'calls #error' do
  24. expect(service).not_to receive(:success)
  25. expect(service).to receive(:error)
  26. subject rescue nil
  27. end
  28. end
  29. context 'committing result to database succeeds' do
  30. before do
  31. allow_any_instance_of(PKParse::Client).to receive(:parse_base64).and_return(client_response)
  32. end
  33. it 'creates some new pokemon' do
  34. expect { subject }.to change { Pokemon.count }.by(1)
  35. end
  36. it 'calls #success' do
  37. expect(service).to receive(:success).once
  38. expect(service).not_to receive(:error)
  39. subject
  40. end
  41. end
  42. end
  43. context 'parsing fails' do
  44. before do
  45. allow_any_instance_of(PKParse::Client).to(
  46. receive(:parse_base64).and_raise(PKParse::Error.new(StandardError.new)),
  47. )
  48. end
  49. it 'does not create any new pokemon' do
  50. expect(service).not_to receive(:success)
  51. expect(service).to receive(:error)
  52. expect { subject }.to change { Pokemon.count }.by(0)
  53. end
  54. end
  55. context '#success' do
  56. it 'calls super method' do
  57. allow_any_instance_of(PKParse::Client).to receive(:parse_base64).and_return(client_response)
  58. expect(service).to receive(:success).once
  59. expect_any_instance_of(service.class.superclass).to receive(:success).once
  60. subject
  61. end
  62. end
  63. end
  64. end