create_pokemon_from_base64_service_spec.rb 2.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. # frozen_string_literal: true
  2. require 'rails_helper'
  3. RSpec.describe CreatePokemonFromBase64Service, type: :service do
  4. describe '#execute' do
  5. subject(:execute) { service.execute(encoded_pokemon) }
  6. let(:service) { described_class.new }
  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(
  15. receive(:parse_base64).and_return(client_response),
  16. )
  17. allow(service).to receive(:success)
  18. allow(service).to receive(:error)
  19. end
  20. context 'when parsing succeeds' do
  21. context 'when committing result to database fails' do
  22. before do
  23. allow(Pokemon)
  24. .to receive(:create!).and_raise(ActiveRecord::ActiveRecordError.new)
  25. end
  26. it 'does not create any new pokemon' do
  27. # expect{execute}.to raise_error 'canned failure'
  28. expect { (execute rescue nil) }.to change(Pokemon, :count).by(0)
  29. end
  30. it 'calls #error' do
  31. execute rescue nil
  32. expect(service).not_to have_received(:success)
  33. expect(service).to have_received(:error)
  34. end
  35. end
  36. context 'when committing result to database succeeds' do
  37. before do
  38. allow_any_instance_of(PKParse::Client)
  39. .to receive(:parse_base64).and_return(client_response)
  40. end
  41. it 'creates some new pokemon' do
  42. expect { execute }.to change(Pokemon, :count).by(1)
  43. end
  44. it 'calls #success' do
  45. execute
  46. expect(service).to have_received(:success).once
  47. expect(service).not_to have_received(:error)
  48. end
  49. end
  50. end
  51. context 'when parsing fails' do
  52. before do
  53. allow_any_instance_of(PKParse::Client)
  54. .to(receive(:parse_base64)
  55. .and_raise(PKParse::Error.new(StandardError.new)))
  56. end
  57. it 'does not create any new pokemon' do
  58. expect { execute }.to change(Pokemon, :count).by(0)
  59. expect(service).not_to have_received(:success)
  60. expect(service).to have_received(:error)
  61. end
  62. end
  63. describe '#success' do
  64. it 'calls super method' do
  65. allow_any_instance_of(PKParse::Client)
  66. .to receive(:parse_base64).and_return(client_response)
  67. expect_any_instance_of(service.class.superclass)
  68. .to receive(:success).once
  69. execute
  70. expect(service).to have_received(:success).once
  71. end
  72. end
  73. end
  74. end